Is there anyway to unit test a filter as below?
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String param = request.getParameter("param");
if (param == null) {
response.sendError(400, "param can't be null");
return;
}
Yes, there is, here is one way. Here I am mocking HttpServletRequest and HttpServletResponse and asserting on methods call by defining expectations.Here I am using JMock.
public class SampleFilterTest {
private Mockery context = new Mockery();
private SampleFilter sampleFilter = new SampleFilter();
private HttpServletRequest request;
private HttpServletResponse response;
@BeforeMethod
public void setUp() throws Exception {
request = context.mock(HttpServletRequest.class);
response = context.mock(HttpServletResponse.class);
}
@Test
public void sampleFilterTest() throws IOException, ServletException {
context.checking(new Expectations() {{
oneOf(request).getParameter("param");
will(returnValue(null));
oneOf(response).sendError(400, "param can't be null");
}});
sampleFilter.doFilter(request, response, null);
}
}
Here I am saying when request.getParmeter is called with "param" then return null, and response.sendError, with 400, and "param can't be null" parameters,should be called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With