Testing with Mockito my API, found very strange thing to me. Creating new User with id property not null, invoke mock of save(user) and getting user.id is null. "Real" save method works different, it saves entity and sets it's id property to unique long value, not null. Code service layer:
@Override
public Long save(User user) {
userDao.save(user);
return user.getId();
}
Controller of API:
@RequestMapping(value = "/user", method = RequestMethod.POST, produces = {"application/json"})
@ResponseStatus(HttpStatus.OK)
public @ResponseBody String addUser(@RequestBody String jsonString) {
User user = User.fromJson(jsonString);
userService.save(user);
return user.toJson();
}
And test:
@Test
public void addUser() throws Exception {
Role role = new Role(1L, "ROLE_USER");
User user = new User (1L, "Test user", "Test password", true, role);
when(roleService.findByName(role.getName())).thenReturn(role);
when(userService.save(user)).thenReturn(1L);
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/user").content(user.toJson())).andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentType("application/json"))
.andReturn();
assertEquals(user.toJson(), result.getResponse().getContentAsString());
verify(userService).save(user);
}
which never passed because expected user with id=1 and actual is user with id=null. Please help find which thing can set user.id to null? Once again, service method (and dao) save works perfect.
Aucun commentaire:
Enregistrer un commentaire