我在用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);问题是,在测试类时,我得到了错误消息:
xxx.PortalServletTest.testSuccesfulRequest(PortalServletTest.java:140) requestDispatcher.forward(,);需要1次:-> 但却是两次。不想要的调用: xxx.PortalServlet.addRequestHeaders(PortalServlet.java:144)上的-> 在xxx.PortalServletTest.testSuccesfulRequest(PortalServletTest.java:140)
如果我单独运行每个测试,它们就可以通过测试。看起来每个测试的前向PortalServlet都是两次计数。对如何解决这个问题有什么建议吗?
提前谢谢。
发布于 2017-01-09 09:01:57
除了@GhostCat所写的内容外,我认为您应该在测试之前对所有模拟对象进行重置:
@Before
public void before() {
Mockito.reset(/*mocked objects to reset*/)
// mock them here or in individual tests
}发布于 2017-01-09 08:38:20
您正在使用@BeforeClass来配置模拟对象。
在执行测试类中的@之前,该方法称为。
您只需尝试将其更改为“以前”!
换句话说:在进行任何测试之前,您可以配置您的模拟以允许one调用。但是,您正在运行多个测试。如果您假设您的模拟都是以相同的方式使用的,那么您只需每次为每个@Test重新配置,每次都是。
给出你的评论:这是
verify(rd, times(2)).forward ...工作/帮助?
发布于 2020-06-15 12:09:51
如果您使用的是Mockito BDD,那么按照下面的步骤执行。
then(empRepository).should(times(3)).findById(emp.getId());https://stackoverflow.com/questions/41543880
复制相似问题