반응형

2021/02/17 - [Development/Java] - Spring Boot Test Case 작성에 대한 생각 - Service Test

2021/02/17 - [Development/Java] - Spring Boot Test Case 작성에 대한 생각 - Repository Test

Repository, Service 에 대한 테스트를 살펴봤으니 이제 Controller 테스트를 확인해보자. Controller Test 에는 @WebMvcTest 를 사용했다. Controller 는 확인해야 할 부분이 다음과 같다. 

1. request 를 요청한 url 과 파라메터가 정확한지 여부.
2. 정상 처리 되었을데 요구한 응답을 보내주는지.
3. 비정상일때에 response 에 상태 코드가 정확히 전달 되는지. 

@RunWith(SpringRunner.class)
@WebMvcTest(UserRestController.class)
public class UserRestControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private UserService userService;

    @Test
    public void getUsers() throws Exception {

        when(userService.findAll())
                .thenReturn(Arrays.asList(
                        Users.builder()
                                .email("test@test.com")
                                .name("test")
                                .status(UserStatus.APPLIED)
                                .build()
                ));

        this.mockMvc.perform(get("/users"))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(jsonPath("@[0].email").value("test@test.com"));

    }
}

테스트케이스를 통해서 response 로 받는 내용과 상태 코드, 그리고 body 에 있는 내용들을 확인 해 볼 수 있다. 

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Content-Type:"application/json"]
     Content type = application/json
             Body = [{"email":"test@test.com","name":"test","userStatus":"APPLIED"}]
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

그리고 print() 를 했기 때문에 콘솔 창에 위와 같은 결과도 같이 확인 해 볼 수 있다. 

그리고 잘못된 결과값이 나올 경우에도 response 가 잘 리턴 되는지 확인해 봐야 한다.

@Test
public void getUserNotFoundException() throws Exception {

  when(userService.findUserById("test11@test.com"))
    .thenThrow(
      new RuntimeException("User not found")
  );

  this.mockMvc.perform(get("/users/test11@test.com"))
    .andDo(print())
    .andExpect(status().isBadRequest());
}


위 테스트는 파라메터로 "test11@test.com" 을 보냈으나 사용자가 존재하지 않을때 400 error 와 메세지를 보내는 경우이다. 

MockHttpServletResponse:
           Status = 400
    Error message = null
          Headers = [Content-Type:"text/plain;charset=UTF-8", Content-Length:"14"]
     Content type = text/plain;charset=UTF-8
             Body = User not found
    Forwarded URL = null
   Redirected URL = null

결과로 400 에러가 전달 되며 Body 에는 메세지가 써있다. 

Controller 테스트에서는 고려해야 할 것들이 많은것 같다. request 를 받고 response 를 보내야 하는 곳이기 때문에 파라메터에 대한 검증과 상태코드, response 값과 message 들이 잘 구성되어있어야 한다. Status 코드가 200이 떨어졌을때 보다는 200이 아닌경우의 상황을 더 많이 고려해야 되지 않을까 생각이 된다. 

주의사항) 제 생각을 기준으로 작성하고 만든 소스코드이고 의견이기 때문에 틀린 부분이 있을수 있습니다.

728x90
반응형

+ Recent posts