ServletRequest
, ServletResponse
and FilterChain
are all interfaces, so you can easily create test stubs for them, either by hand or using a mocking framework.
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.
Inject a mock ModeService.
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());
}
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.
... 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).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…