I'm trying to test my servlet to see if it calls my DAOService
with some passed parameters from the session but running into this problem
The log:
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)
The code
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"));
Any tip is appreciated
CodePudding user response:
As for initialising MockHttpServletRequest
, you should use the Spring provided builder. Since it is a class offered by the Spring framework (and is not a Mockito mock), using Mockito to mock its methods will result in an error.
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"));
Moreover, your supplierDAO
mock is useless. After mocking an object, you need to inject it into the code under test. It is usually done by passing the mock as a function parameter. Whereas in your test, you're trying to verify calls on a mock that was never used.