java模拟执行PUT函数的控制器
我试图创建一个模拟我的控制器来更新用户内部的数据。从代码中,我尝试只更新电子邮件、密码和年龄。我们应该这样做吗?因为我对Mockito和Junit还很陌生
Controller Mock
@Test
public void testUpdateUserController() throws Exception{
String username = "User";
String email = "user@email.com";
String password = "password123";
int age = 90;
Mockito.when(userService.updateUser(username,email,password,age)).then(invocationOnMock -> {
User user = new User();
user.setUsername("User");
user.setEmail("user@user.com");
user.setPassword("123456");
user.setAge(12);
user.setAddress("11111");
user.setIsActive(true);
return Optional.of(user);
});
mockMvc.perform(MockMvcRequestBuilders.put(BASE_URL + "/users/{username}",username)
.contentType(MediaType.APPLICATION_JSON_UTF8)).andExpect(MockMvcResultMatchers.status().isOk());
Mockito.verify(userService, Mockito.times(1)).updateUser(userCaptor.capture(),emailCaptor.capture(),passwordCaptor.capture(),ageCaptor.capture());
Assert.assertEquals("User", userCaptor.getValue());
Assert.assertEquals("user@email.com", emailCaptor.getValue());
Assert.assertEquals("password123", passwordCaptor.getValue());
Assert.assertEquals("90", ageCaptor.getValue());
Assert.assertEquals("11111", addressCaptor.getValue());
}
UserServiceImpl
@Override
public boolean updateUser(String username, String email, String password, Integer age) {
Optional<User> userList = userRepository.findByUsernameAndIsActiveTrue(username);
if (userList.isPresent()) {
User user = userList.get();
user.setEmail(email);
user.setPassword(password);
user.setAge(age);
userRepository.save(user);
return true;
} else {
return false;
}
}
# 1 楼答案
下面是我的一个MVC模拟代码示例