mardi 28 juillet 2015

Servlet JUnit test using Jmockit

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

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:

Unit 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);
    }

}

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?

Aucun commentaire:

Enregistrer un commentaire