如何使用 jUnit 对 Servlet 过滤器进行单元测试? [英] How do I unit test a Servlet Filter with jUnit?
问题描述
已实现doFilter()
.如何使用 jUnit 正确覆盖过滤器?
Implemented doFilter()
. How to properly cover Filter with jUnit ?
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws java.io.IOException, javax.servlet.ServletException
{
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String currentURL = request.getRequestURI();
if (!currentURL.equals("/maintenance.jsp") && modeService.getOnline())
{
response.sendRedirect("/maintenance.jsp");
}
filterChain.doFilter(servletRequest, servletResponse);
}
推荐答案
ServletRequest
, ServletResponse
和 FilterChain
都是接口,所以你可以手动或使用模拟框架轻松为它们创建测试存根.
ServletRequest
, ServletResponse
and FilterChain
are all interfaces, so you can easily create test stubs for them, either by hand or using a mocking framework.
使模拟对象可配置,以便您可以准备对 getRequestURI()
的预设响应,以便您可以查询 ServletResponse 以断言 sendRedirect 已被调用.
Make the mock objects configurable so that you can prepare a canned response to getRequestURI()
and so that you can query the ServletResponse to assert that sendRedirect has been invoked.
注入一个模拟 ModeService.
Inject a mock ModeService.
调用 doFilter 并传递模拟 ServletRequest、ServletResponse 和 FilterChain 作为其参数.
Invoke doFilter passing the mock ServletRequest, ServletResponse and FilterChain as its parameters.
@Test
public void testSomethingAboutDoFilter() {
MyFilter filterUnderTest = new MyFilter();
filterUnderTest.setModeService(new MockModeService(ModeService.ONLINE));
MockFilterChain mockChain = new MockFilterChain();
MockServletRequest req = new MockServletRequest("/maintenance.jsp");
MockServletResponse rsp = new MockServletResponse();
filterUnderTest.doFilter(req, rsp, mockChain);
assertEquals("/maintenance.jsp",rsp.getLastRedirect());
}
在实践中,您需要将设置移动到@Before setUp()
方法中,并编写更多@Test 方法来覆盖所有可能的执行路径.
In practice you'll want to move the setup into an @Before setUp()
method, and write more @Test methods to cover every possible execution path.
...而且您可能会使用像 JMock 或 Mockito 这样的模拟框架来创建模拟,而不是假设的 MockModeService
等.我在这里使用过.
... and you'd probably use a mocking framework like JMock or Mockito to create mocks, rather than the hypothetical MockModeService
etc. I've used here.
这是一种单元测试方法,而不是集成测试.您只是在测试被测单元(和测试代码).
This is a unit testing approach, as opposed to an integration test. You are only exercising the unit under test (and the test code).
这篇关于如何使用 jUnit 对 Servlet 过滤器进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!