code : https://github.com/mijosan/test-practice/tree/master/mybatis
@RequiredArgsConstructor
@RestController
public class UserController {
private final UserService userService;
@PostMapping(value="/v1/user")
public ResponseEntity<ResponseDto> postUser(@RequestBody UserSaveRequestDto userSaveRequestDto) {
Long userId = userService.insertUser(userSaveRequestDto);
return CommonUtil.getResponseEntity(UserResponseDto.builder()
.userId(userId)
.build()
, HttpStatus.OK
, "회원 등록 완료");
}
}
Here is my test code
@WebMvcTest
public class UserControllerTest {
@Autowired
MockMvc mockMvc;
@Autowired
ObjectMapper objectMapper;
@MockBean
UserService userService;
UserSaveRequestDto userSaveRequestDto;
@BeforeEach
void setUp() {
userSaveRequestDto = UserSaveRequestDto.builder()
.userName("test")
.userPhoneNumber("01026137832")
.build();
}
@DisplayName("MockMvc를 이용한 postUser slice 테스트")
@Test
public void postUserTest() throws Exception {
// given
given(userService.insertUser(userSaveRequestDto)).willReturn(1L);
String content = objectMapper.writeValueAsString(userSaveRequestDto);
// when
MvcResult mvcResult = mockMvc.perform(post("/v1/user")
.contentType(MediaType.APPLICATION_JSON)
.content(content))
.andExpect(status().isOk())
.andReturn();
// then
String result = mvcResult.getResponse().getContentAsString();
System.out.println(result);
}
}
and I received an exception of "java.lang.AssertionError: Status expected:<200> but was:<500>"
However, it works well if you test it with a swagger.
Where is the cause?
If you modify you test code to
...
.content(content))
.andDo(result -> {
result.getResolvedException().printStackTrace();
})
.andExpect(status().isOk())
...
you will find in a log
org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class com.example.mybatis.dto.ResponseDto
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:220)
at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:219)
at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:78)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:124)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894)
....
The cause of the 500 is that controller is not able to serialize your ResponseDto
. You need to add lombok.Getter
on your ResponseDto
.