Writing some tests for my webapp with API, testing controllers methods. Controllers uses service methods which I want to mock. Test code:
@Mock
private UserService userService;
@Mock
private PasswordEncoder passwordEncoder;
@InjectMocks
private UserApi userApi;
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(userApi).build();
@Test
public void addUser() throws Exception {
Role role = new Role(1L, "ROLE_USER");
User user = new User (null, "Test user", "Test password", true, role);
when(roleService.findByName(role.getName())).thenReturn(role);
when(passwordEncoder.encode(user.getPassword())).thenReturn("Encoded password");
when(userService.save(user)).thenReturn(1L);
mockMvc.perform(MockMvcRequestBuilders.post("/user").content(user.toJson())).andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentType("application/json"))
.andExpect(content().string(user.toJson()));
}
When UserService.save(user) called it sets id property of user to some unique Long value if it was null. Can I set Mock of UserService.save(user) to change id of saved user, as real save() do? Same with PasswordEncoder, when PasswordEncoder.encode(string) is called it changes string value to encoded value, how say Mock of PasswordEncoder do the same?
Aucun commentaire:
Enregistrer un commentaire