我正在尝试测试我的 servlet,看看它是否使用会话中传递的一些参数调用我的
DAOService
,但遇到了这个问题
日志:
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
at Servlet.SupplierServletTest.supplierServlet_StandardTest(SupplierServletTest.java:32)
代码
SupplierServlet supplierServlet = new SupplierServlet();
MockHttpServletRequest request = new MockMvcRequestBuilders.get("/SupplierServlet").buildRequest(new MockServletContext());
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpSession session = new MockHttpSession();
when(request.getSession()).thenReturn(session); //This is the line 32 that the log mentioned, I deleted the session part and the problem was the same for the following lines
when(request.getParameter("Name")).thenReturn("test");
when(request.getParameter("Address")).thenReturn("test");
when(request.getParameter("Phone")).thenReturn("1234");
supplierServlet.processRequest(request, response);
supplierDAO = mock(SupplierDAO.class);
verify(supplierDAO).newSupplier(new Supplier("test", "test", "1234"));
如有任何提示,我们将不胜感激
至于初始化
MockHttpServletRequest
,您应该使用Spring提供的构建器。由于它是 Spring 框架提供的类(并且不是 Mockito 模拟),因此使用 Mockito 模拟其方法将导致错误。
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpSession session = new MockHttpSession();
MockHttpServletRequest request = MockMvcRequestBuilders.get("/SupplierServlet")
.session(session)
.param("Name", "test")
.param("Address", "test")
.param("Phone", "1234")
.buildRequest(new MockServletContext());
supplierServlet.processRequest(request, response);
supplierDAO = mock(SupplierDAO.class);
verify(supplierDAO).newSupplier(new Supplier("test", "test", "1234"));
此外,你的
supplierDAO
模拟毫无用处。模拟对象后,您需要将其注入到被测试的代码中。通常通过将模拟作为函数参数传递来完成。而在您的测试中,您试图验证对从未使用过的模拟的调用。
如果需要模拟行为,请使用 Mockito 模拟的模拟。
我在使用以下测试方法时遇到了同样的错误;
@Test
void testLogicWhenHttpCallShouldForwardToHttp() {
//Given
HttpServletRequest request = new MockHttpServletRequest();
HttpServletResponse response = new MockHttpServletResponse();
String url = "www.testdomain.com/api/route";
//When
Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("https://" + url));
//... rest of the code
}
通过如上所述更改模拟来修复它;
@Test
void testLogicWhenHttpCallShouldForwardToHttp() {
//Given
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
String url = "www.testdomain.com/api/route";
//When
Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("https://" + url));
//... rest of the code
}