Reputation: 9010
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?
Upvotes: 1
Views: 3204
Reputation: 952
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()
);
}
}
Upvotes: 2