使用Jmockit Servlet的JUnit测试(Servlet JUnit test using

2019-10-24 06:34发布

我想建立使用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结果状态代码?

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

}


文章来源: Servlet JUnit test using Jmockit