如何将 Mock HttpServletRequest 与 mockMvc 一起使用

How to use Mock HttpServletRequest with mockMvc

我正在模拟 HttpServletRequest 和 Mockito 来模拟控制器层,但我得到了错误:

Argument(s) are different! Wanted: service.validateDeletingProcessBoard( org.springframework.mock.web.MockHttpServletRequest@29caf222, "603b408b-4eb2-4d01-ab90-d30277874415" ); -> at com.valuestreamer.backend.process.controller.ProcessboardAdminControllerTest.validateDeletingProcessBoardStatus200(ProcessboardAdminControllerTest.java:121) Actual invocations have different arguments: service.validateDeletingProcessBoard( org.springframework.mock.web.MockHttpServletRequest@68b734a8, "603b408b-4eb2-4d01-ab90-d30277874415" );

这是我的代码:

MockHttpServletRequest request = new MockHttpServletRequest();
when(this.service.validateDeletingProcessBoard(request,id)).thenReturn(object);
MvcResult result = mockMvc.perform("/api/...").andExpect(status().isOk()).andReturn();

控制器的结果为空。 我认为错误可能是因为对象请求的时间和服务请求不同? 我怎么能通过这个案子呢?

你是对的,抛出这个异常是因为存根设置与测试执行期间传递的对象不匹配。

.toString() 在 Stacktrace 中表示:

org.springframework.mock.web.__MockHttpServletRequest@29caf222__, "603b408b-4eb2-4d01-ab90-d30277874415"            
org.springframework.mock.web.__MockHttpServletRequest@68b734a8__, "603b408b-4eb2-4d01-ab90-d30277874415"

id 参数确实匹配,但与您的 MockHttpServletRequest 的实例不匹配。

您可以通过更 open 存根设置来解决这个问题,它不检查 MockHttpServletRequest

的相等性
when(this.service.validateDeletingProcessBoard(any(MockHttpServletRequest.class),eq(id))).thenReturn(object);

确保 any()eq() 都使用 org.mockito.ArgumentMatchers