본문으로 바로가기

Kotlin으로 개발하는 Spring Boot Web MVC #5

목차

    실습 환경

    • IntelliJ
    • Kotlin
    • Gradle
    • JDK 11
    • Spring Boot 2.6.2

    실습 코드

    https://github.com/0n1dev/kotlin-spring-practice

     

    GitHub - 0n1dev/kotlin-spring-practice: 인프런 강의

    인프런 강의. Contribute to 0n1dev/kotlin-spring-practice development by creating an account on GitHub.

    github.com

    JUnit

    @WebMvcTest
    @AutoConfigureMockMvc
    internal class ExceptionApiControllerTest {
    
        @Autowired
        lateinit var mockMvc: MockMvc
    
        @Test
        fun indexOutOfBoundTest() {
            mockMvc.perform(
                get("/api/exception/index-out-of-bound")
            ).andExpect(
                status().isOk
            ).andDo(print())
        }
    
        @Test
        fun getTest() {
            val queryParams = LinkedMultiValueMap<String, String>()
    
            queryParams.add("name", "0n1dev")
            queryParams.add("age", "20")
    
            mockMvc.perform(
                get("/api/exception")
                    .queryParams(queryParams)
            ).andExpect(
                status().isOk
            ).andExpect(
                content().string("0n1dev 20")
            ).andDo(print())
        }
    
        @Test
        fun getFailTest() {
            val queryParams = LinkedMultiValueMap<String, String>()
    
            queryParams.add("name", "0n1dev")
            queryParams.add("age", "1")
    
            mockMvc.perform(
                get("/api/exception")
                    .queryParams(queryParams)
            ).andExpect(
                status().isBadRequest
            ).andExpect(
                content().contentType("application/json")
            ).andExpect(
                jsonPath("\$.result_code").value("Fail")
            ).andDo(print())
        }
    
        @Test
        fun postTest() {
            val userRequest = UserRequest().apply {
                this.name = "0n1dev"
                this.age = 20
                this.phoneNumber = "010-3333-3333"
                this.address = "fawefawf"
                this.email = "test@naver.com"
                this.createdAt = "2022-01-16 18:50:00"
            }
    
            val json = jacksonObjectMapper().writeValueAsString(userRequest)
    
            mockMvc.perform(
                post("/api/exception")
                    .content(json)
                    .contentType("application/json")
                    .accept("application/json")
            ).andExpect(
                status().`is`(200)
            ).andDo(print())
        }
    }