使用Jmockit进行Servlet JUnit测试

时间:2015-07-29 01:20:00

标签: java unit-testing servlets junit jmockit

我想使用JUnit和JMockit为Servlet构建单元测试。

我有一个ImageServlet,它将图像ID(String)作为请求参数,如果ID为null,则servlet会抛出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的结果状态代码?

1 个答案:

答案 0 :(得分:1)

我不熟悉所有最新的JMockit注入内容,所以我使用JMockits支持“假货”。

@RunWith(JMockit.class)
public class ImageServletTest3 {

     @Test
    public void testImageNotFound() throws Exception {
        ImageServlet servlet = new ImageServlet();

        servlet.doGet(
            new MockUp<HttpServletRequest>() {
              @Mock
              public String getParameter(String id){
                return null;
              }

            }.getMockInstance(),
            new MockUp<HttpServletResponse>() {
              @Mock
              public void sendError(int num){
                Assert.assertThat(num, IsEqual.equalTo(404));               
              }             
            }.getMockInstance()
       );
    }

}