使用 servlet 和会话进行测试时获取 MissingMethodInvocationException

Getting MissingMethodInvocationException while testing with servlet and session

我正在尝试测试我的 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 框架提供的 class(并且不是 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 mock 毫无用处。模拟对象后,您需要将其注入到被测代码中。通常通过将模拟作为函数参数传递来完成。而在您的测试中,您正在尝试验证从未使用过的模拟上的调用。