So we’re almost at our goal to test-drive our spring web-mvc application. We’re using spring security to secure URLs or methods and we want to use Spring-Web-Mvc to test the controllers. The problem is: Spring security relies on a FilterChain defined in the 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 only load the usual application context stuff:
@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 one can see, we set up our web app so that when calling /home an annonymus user will be prompted to log in. This is working fine with the web.xml in place but we have no idea how to integrate this into our tests.
Is there any way to add a filter to spring-test-mvc?
Right now I’m thinking I might have to start at the GenericWebContextLoader, dig into the MockRequestDipatcher which implements RequestDispatcher, add a filter there somehow and then tell the GenericWebContextLoader to use my implementation… But I’m quite unfamiliar with the whole web stack and would prefer an easier solution that helps me avoid digging into that stuff obviously…
Any ideas / solutions out there?
How would I add a filter by hand anyway? web.xml can’t be the only place to do it…
Thanks!
Maybe you could mock the filter chain. There is a class in Spring for doing that.
The code would look something like:
Then you can add the org.springframework.web.filter.DelegatingFilterProxy instance to the
chain in your code.
Something like:
See also this forum thread.