如何解决测试非存储库方法时,如何执行等同于“ when,thenReturn”的操作
我正在Spring Boot JUnit中编写一些测试代码,并且在使用存储库方法的测试案例中成功使用了"when,thenReturn"
,如下所示。
@ExtendWith(SpringExtension.class)
@WebMvcTest
public class PictionarizerapiUserControllerTests {
@MockBean
private UserRepository userRepository;
@MockBean
private UserController userController;
@Autowired
private MockMvc mockMvc;
@Test
@DisplayName("When an update request is sent,the User data gets updated properly,and the updated User data gets returned in a form of JSON")
public void testUpdateUser() throws Exception {
// User before update
User existingUser = new User();
existingUser.setId(28);
existingUser.setName("Alex");
......
......
// return the User (before update) that is fetched by UserRepository#findById() with ID=28
when(userRepository.findById(28)).thenReturn(Optional.of(existingUser));
// UserRepository#save() returns the fetched entity as it is
when(userRepository.save(any())).thenAnswer((invocation) -> invocation.getArguments()[0]);
......
......
我以为自己也可以为自己编写的控制器方法编写一个测试用例,然后尝试执行“ when,thenReturn”,如下所示。
@Test
@DisplayName("When correct login information is given and the matched user is fetched")
public void testCheckIfValidUserFound() throws Exception {
Integer userIdObj = Integer.valueOf(28);
String requestEmail = "alex.armstrong@example.com";
String requestPassword = "MajorStateAlchemist";
when(userController.checkIfValidUser(requestEmail,requestPassword)).thenReturn(Optional.of(userIdObj));
......
......
}
但是,我收到一条错误消息The method thenReturn(ResponseEntity<capture#1-of ?>) in the type OngoingStubbing<ResponseEntity<capture#1-of ?>> is not applicable for the arguments (Optional<Integer>)
。经过研究,我了解到只有在测试存储库方法时才可以使用"when,thenReturn"
语法,这些存储库方法是JPA中内置的方法,例如findById()
等(除非我弄错了),对于我来说,它不起作用,因为我要测试的是我自己创建的方法,而不是JPA内置的存储库方法。
这是我的问题。
在测试除存储库方法以外的内容时,如何编写与"when,thenReturn"
等效的内容?
更新
这是我自己的方法的定义方式。
@RequestMapping(value = "/login",method = RequestMethod.GET)
public ResponseEntity<?> checkIfValidUser(
@RequestParam("email") String email,@RequestParam("password") String password) {
int userId = 0;
List<User> userList = repository.findAll();
for(User user: userList) {
String userEmail = user.getEmail();
String userPassword = user.getPassword();
String inputEmail = email;
String inputPassword = password;
if(userEmail.equals(inputEmail) && userPassword.equals(inputPassword)) {
userId = user.getId();
}
}
if(userId > 0) {
Integer userIdObj = Integer.valueOf(userId);
return new ResponseEntity<>(userIdObj,HttpStatus.OK);
} else {
return new ResponseEntity<>(
new Error("The email address and the password don't match"),HttpStatus.NOT_FOUND
);
}
}
解决方法
似乎您要测试的方法是testCheckIfValidUserFound()
,因此您不应该像这样模拟方法本身。
when(userController.checkIfValidUser(requestEmail,requestPassword)).thenReturn(Optional.of(userIdObj));
相反,您应该模拟的方法是userRepository.findAll()
,因为这是您要在控制器的checkIfValidUser
方法内调用的存储库方法。
因此,您的“何时返回”部分应如下所示。
when(userRepository.findAll()).thenReturn(Collections.singletonList(esixtingUser));
,当您要检查测试是否返回正确的值时,通常需要指定要检查的键的值,但是在这种情况下,根据您的checkIfValidUser
方法,它只会返回一个整数,如果搜索成功,因此在使用jsonPath
进行断言时,美元符号不应该有任何说明。
因此,在模拟存储库之后,您可以像这样执行获取请求。
mockMvc.perform(MockMvcRequestBuilders.get("/login")
.param("email",requestEmail)
.param("password",requestPassword)
.with(request -> {
request.setMethod("GET")<
return request;
}))
.andExpect(MockMvcResultMatchers.status().is(HttpStatus.OK.value()))
.andExpect(jsonPath("$").value(28));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。