因此,我们的目标是测试我们的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.xml不是唯一可以做到的地方……
谢谢!
最佳答案
也许你可以模拟过滤器链.春天有一个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论坛帖子.
相关文章
- 使用Spring Mvc测试测试Spring Security Controller
- java - Spring的MockMvc用于单元测试或集成测试吗?
- Spring MVC测试(安全集成测试),JSESSIONID不存在
- java - 在Spring Security中使用自定义过滤器时,Spring单元测试MockMvc失败
- java - 使用Spring的DomainClassConverter功能进行单元测试
- java - 使用Spring MVC测试来单元测试multipart POST请求
- java - 如何使用注释对Spring Controller进行单元测试?
- 单元测试 - 使用Sonar对Jenkins进行spring-test-mvc的问题
转载注明原文:java – 使用Spring-Test-MVC进行单元测试Spring-Security – 集成FilterChain / ServletFilter - 代码日志