代码: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
, "회원 등록 완료");
}
}
这是我的测试代码
@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);
}
}
我收到一个异常“java.lang.assertionerror:status expected:<200>but was:<500>”
但是,如果您 swagger 地测试它,它会很好地工作。
原因在哪里?
1条答案
按热度按时间uemypmqf1#
如果将测试代码修改为
你会在日志中找到
500的原因是控制器无法序列化
ResponseDto
. 你需要加上lombok.Getter
在你的ResponseDto
.