因此,我们几乎达到了测试驱动spring web-mvc应用程序的目标。我们使用spring安全性来保护URL或方法,并希望使用Spring-Web-Mvc来测试控制器。问题是: Spring安全性依赖于web.xml中定义的FilterChain:
<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>而spring-web-mvc即使使用custom context loader也只能加载通常的应用程序上下文内容:
@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")));
}
}正如大家所看到的,我们设置了我们的web应用程序,以便在调用/home时会提示匿名用户登录。这在web.xml中工作得很好,但我们不知道如何将其集成到我们的测试中。
有没有办法给spring-test-mvc添加一个过滤器?
现在我在想,我可能必须从GenericWebContextLoader开始,深入研究实现RequestDispatcher的MockRequestDipatcher,以某种方式在那里添加一个过滤器,然后告诉GenericWebContextLoader使用我的实现……但我对整个web堆栈都很不熟悉,我更喜欢一种更简单的解决方案,它可以帮助我避免明显地挖掘那些东西……
有什么想法/解决方案吗?
我该如何手动添加过滤器呢?web.xml不可能是唯一这样做的地方...
谢谢!
发布于 2012-06-14 17:42:25
也许你可以模仿一下过滤链。Spring中有一个class可以做到这一点。代码看起来像这样:
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);然后,您可以在代码中将org.springframework.web.filter.DelegatingFilterProxy实例添加到链中。类似于:
另请参阅this论坛线程。
https://stackoverflow.com/questions/10999631
复制相似问题