我正在使用Junit和Mockito进行向前测试。
这是PortalServletTest类的一部分:

@SuppressWarnings("serial")
@BeforeClass
public static void setUpTests() {
    when(request.getRequestDispatcher(Mockito.anyString())).thenReturn(rd);
    when(request.getSession()).thenReturn(httpSession);
    when(httpSession.getServletContext()).thenReturn(servletContext);
    when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
    when(configurationManager.getConfiguration()).thenReturn(configuration);
    List<List<String>> mandatoryHeaders = new ArrayList<List<String>>();
    mandatoryHeaders.add(new ArrayList<String>() {
        {
            add("HTTP_XXXX");
            add("http-xxxx");
        }
    });

    List<List<String>> optionalHeaders = new ArrayList<List<String>>();
    optionalHeaders.add(new ArrayList<String>() {
        {
            add("HTTP_YYYY");
            add("http-yyyy");
        }
    });

    when(configuration.getIdentificationHeaderFields()).thenReturn(mandatoryHeaders);
    when(configuration.getOptionalHeaderFields()).thenReturn(optionalHeaders);

}

@Test
public void testMissingHeadersRequest() throws IOException {
    when(request.getHeader(Mockito.anyString())).thenReturn(null);
    target().path("/portal").request().get();
    Mockito.verify(response, times(1)).sendError(HttpServletResponse.SC_USE_PROXY, PortalServlet.MISSING_HEADERS_MSG);
}

@Test
public void testSuccesfulRequest() throws IOException, ServletException {
    Mockito.doAnswer(new Answer<Object>() {
        public Object answer(InvocationOnMock invocation) {
            Object[] args = invocation.getArguments();
            String headerName = (String) args[0];
            return headerName;
        }
    }).when(request).getHeader(Mockito.anyString());
    target().path("/portal").request().get();
    verify(rd).forward(Mockito.any(ServletRequest.class), Mockito.any(ServletResponse.class));
}
PortalServlet代码:
RequestDispatcher rd = request.getRequestDispatcher("index.html");
        rd.forward(mutableRequest, response);

问题是,在测试类时,我收到错误消息:

requestDispatcher.forward(,);
想要1次:
->在xxx.PortalServletTest.testSuccesfulRequest(PortalServletTest.java:140)

但是是2次。意外调用:
->在xxx.PortalServlet.addRequestHeaders(PortalServlet.java:144)

在xxx.PortalServletTest.testSuccesfulRequest(PortalServletTest.java:140)

如果我分别运行每个测试,则它们可以通过。
看起来PortalServlet的转发对每个测试计数两次。
有什么建议如何解决这个问题?

提前致谢。

最佳答案

除了@GhostCat编写的内容外,我认为您应该在测试之前reset所有模拟对象:

@Before
public void before() {
   Mockito.reset(/*mocked objects to reset*/)
   // mock them here or in individual tests
}

08-18 19:34