我想建立使用JUnit和JMockit一个Servlet单元测试。
我有一个ImageServlet这需要图像ID(字符串)作为请求参数,并且如果ID是空小服务程序会因这种情况下我有测试HTTP状态代码404(未找到):
单元测试:
@RunWith(JMockit.class)
public class ImageServletTest {
@Tested
private ImageServlet servlet;
@Injectable
HttpServletRequest mockHttpServletRequest;
@Injectable
HttpServletResponse mockHttpServletResponse;
@Injectable
PrintWriter printWriter;
@Injectable
ServletOutputStream servletOutputStream;
@Before
public void setUp() throws Exception {
servlet = new ImageServlet();
initMocks(null);
}
private void initMocks(final String imgId) throws Exception {
new NonStrictExpectations() {{
mockHttpServletRequest.getParameter("id");
result = imgId;
mockHttpServletResponse.getWriter();
result = printWriter;
mockHttpServletResponse.getOutputStream();
result = servletOutputStream;
}};
}
@Test
public void testImageNotFound() throws Exception {
servlet.doGet(mockHttpServletRequest, mockHttpServletResponse);
org.junit.Assert.assertTrue(mockHttpServletResponse.getStatus() == HttpServletResponse.SC_NOT_FOUND);
}
}
问题是,我断言失败为mockHttpServletResponse.getStatus()总是返回0,有没有办法让使用JMockit的servlet结果状态代码?