Using Spring -Test-MVC to unit test Spring -Security - FilterChain / ServletFilter Integration

So, we are almost striving to test our spring web-mvc application. We use spring protection to protect URLs or methods, and we want to use Spring-Web-Mvc to test controllers. The problem is this: spring protection depends on the FilterChain defined in web.xml:

<filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> <dispatcher>FORWARD</dispatcher> <dispatcher>REQUEST</dispatcher> </filter-mapping> 

While Spring -web-mvc, even with a custom context loader, can load only regular application context materials:

 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader = WebContextLoader.class, locations = { "file:src/main/webapp/WEB-INF/servlet-context.xml", "file:src/main/webapp/WEB-INF/dw-manager-context.xml" }) public class MvcTest { @Inject protected MockMvc mockMvc; @Test public void loginRequiredTest() throws Exception { mockMvc.perform(get("/home")).andExpect(status().isOk()).andExpect(content().type("text/html;charset=ISO-8859-1")) .andExpect(content().string(containsString("Please Login"))); } } 

As you can see, we configured our web application so that when invoking / home, the user annonymus was prompted to log in. This works fine with web.xml, but we have no idea how to integrate this into our tests.

Can I add a filter in Spring -test-mvc?

Right now, I think that I may have to start with a GenericWebContextLoader , dig into the MockRequestDipatcher that implements RequestDispatcher , add a filter there somehow, and then tell GenericWebContextLoader use my implementation. But I am completely unfamiliar with the entire web stack and would prefer a lighter solution that would help me avoid digging into this material, obviously ...

Any ideas / solutions out there?

How can I add a filter manually? web.xml may not be the only place for this ...

Thanks!

+4
source share
1 answer

Perhaps you could mock the filter chain. There is a class in Spring for this. The code will look something like this:

  MockHttpServletRequest request = new MockHttpServletRequest(); request.setServletPath("/foo/secure/super/somefile.html"); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain chain = new MockFilterChain(true); filterChainProxy.doFilter(request, response, chain); 

Then you can add an instance of org.springframework.web.filter.DelegatingFilterProxy to the chain in your code. Sort of:

See also this forum.

+5
source

All Articles