使用Jmockit进行Servlet JUnit测试

使用Jmockit进行Servlet JUnit测试

问题描述:

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

I want build a unit test for a Servlet using JUnit and JMockit.

我有一个ImageServlet,它将图像ID(字符串)作为请求参数,如果ID为null,则Servlet抛出HTTP状态代码404(未找到) 对于这种情况,我要进行测试:

I have an ImageServlet which takes image IDs (String) as request parameters and if ID is null the servlet throws a HTTP status code 404 (not found) for this scenario I have the test:

单元测试:

@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的结果状态代码?

the problem is that my Assertion fails as mockHttpServletResponse.getStatus() always returns 0, is there a way to get the resulting Status code of the servlet using JMockit?

我对所有最新的JMockit注入工具都不熟悉,因此我使用了JMockits对伪造"的支持.

I'm not familiar with all the latest JMockit injection stuff, so I used JMockits support for "fakes".

@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()
       );
    }

}