使用API編寫我的webapp測試,測試控制器方法。控制器使用我想要模擬的服務方法。 測試代碼:使用模擬方法
@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()));
}
當UserService.save(用戶)調用時都會將用戶的id屬性設置爲一些獨特的長值,如果它爲空。我可以設置UserService.save(用戶)的模擬更改保存的用戶的ID,因爲真正的save()嗎? 與PasswordEncoder相同,當調用PasswordEncoder.encode(string)時,它將字符串值更改爲編碼值,PasswordEncoder的Mock如何執行相同的操作?
謝謝,是的,我喜歡完整性測試:) – zzheads
保存方法(模擬)後用戶的id屬性更改爲null在控制器中調用。 「真正的」save()完全不同,找不到可以在「模擬」版本中設置user.id的內容...... – zzheads