Spring boot 需要在端点后跳过@RequestBody注释中模拟服务方法
我正在尝试为后REST端点编写一个单元测试。我需要使用mockito模拟在上述端点中使用的服务方法。使用模拟mvc触发端点 我在模拟端点中使用的userService.saveUseruser,并返回一个整数作为创建的userId。但mock似乎总是返回0,而不是7777 userId defined。 对于验证,它说参数是不同的!它在端点和我定义的模拟中传递给userServiceuser Mockito验证错误:Spring boot 需要在端点后跳过@RequestBody注释中模拟服务方法,spring-boot,junit,mockito,mockmvc,Spring Boot,Junit,Mockito,Mockmvc,我正在尝试为后REST端点编写一个单元测试。我需要使用mockito模拟在上述端点中使用的服务方法。使用模拟mvc触发端点 我在模拟端点中使用的userService.saveUseruser,并返回一个整数作为创建的userId。但mock似乎总是返回0,而不是7777 userId defined。 对于验证,它说参数是不同的!它在端点和我定义的模拟中传递给userServiceuser Mockito验证错误: Argument(s) are different! Wanted: user
Argument(s) are different! Wanted:
userService.saveUser(
com.foo.dto.User@741f8dbe
);
-> at com.foo.controller.UserControllerTest.saveUser(UserControllerTest.java:104)
Actual invocation has different arguments:
userService.saveUser(
com.foo.dto.User@212dfd39
);
-> at com.foo.controller.UserController.saveUser(UserController.java:45)
Comparison Failure: <Click to see difference>
我想原因就是你说的。您可以使用匹配器传递到您的模拟,这样只要它接收的是特定类型的对象而不是特定对象,它就会返回您想要的:
import static org.mockito.ArgumentMatchers.any;
...
when(userService.saveUser(any(User.class))).thenReturn(userId);
在您使用它时使用的mock,只有当它作为调用的参数接收您在执行时传递的特定对象时,它才会返回您想要的内容。从异常中可以看出,mock希望接收一个引用为com.foo.dto的对象。User@741f8dbe这是您在安装方法中创建的,但它正在接收com.foo.dto。User@212dfd39这是Jackson在反序列化rest调用主体时生成的