我有这种创建用户的方法
@PostMapping()
public ResponseEntity create(@Valid @RequestBody final User user) {
if (userRepository
.findById(user.getId())
.isPresent()) {
throw new UserAlreadyExistsException(user.getId());
}
userRepository.save(user);
return ResponseEntity
.ok()
.build();
}
,我正在尝试使用嘲笑Mvc对其进行测试。
@Test
public void createException() throws Exception {
final User foo = new User(1, "foo");
given(userRepository.findById(foo.findById())).willReturn(Optional.of(foo));
given(userRepository.save(foo)).willReturn(foo);
mvc
.perform(post("/add")
.contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(foo)))
.andExpect(status().is5xxServerError())
}
我期望出现'UserAlreadyExistsException'异常,但我却低于异常并且测试失败。
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is UserAlreadyExistsException: User with id 1 already exists