Pet*_*ete 4 java spring spring-mvc spring-security servlet-filters
因此,我们的目标是测试我们的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>
Run Code Online (Sandbox Code Playgroud)
虽然spring-web-mvc即使使用自定义上下文加载器也只能加载通常的应用程序上下文:
@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")));
}
}
Run Code Online (Sandbox Code Playgroud)
正如人们所看到的,我们建立了我们的web应用程序,以便在调用时/家庭的annonymus用户将被提示登录.这是工作的罚款与地方在web.xml,但我们不知道如何将这种整合到我们的测试.
有没有办法在spring-test-mvc中添加过滤器?
现在我想我可能不得不开始GenericWebContextLoader
,挖掘MockRequestDipatcher
哪个实现RequestDispatcher
,在某种程度上添加一个过滤器然后告诉GenericWebContextLoader
使用我的实现...但我对整个Web堆栈很不熟悉并且更喜欢一个更简单的解决方案,可以帮助我避免深入挖掘这些东西......
有什么想法/解决方案吗?
如何手动添加过滤器?web.xml不是唯一可以做到的地方......
谢谢!
小智 6
也许你可以模拟过滤器链.在Spring中有一个类可以做到这一点.代码看起来像:
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);
Run Code Online (Sandbox Code Playgroud)
然后,您可以将org.springframework.web.filter.DelegatingFilterProxy实例添加到代码中的链中.就像是:
另请参见本论坛的帖子.
归档时间: |
|
查看次数: |
4989 次 |
最近记录: |