首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Spring- test -MVC对Spring-Security进行单元测试--集成FilterChain / ServletFilter

使用Spring- test -MVC对Spring-Security进行单元测试--集成FilterChain / ServletFilter
EN

Stack Overflow用户
提问于 2012-06-12 23:15:02
回答 1查看 5.3K关注 0票数 4

因此,我们几乎达到了测试驱动spring web-mvc应用程序的目标。我们使用spring安全性来保护URL或方法,并希望使用Spring-Web-Mvc来测试控制器。问题是: Spring安全性依赖于web.xml中定义的FilterChain:

代码语言:javascript
复制
<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也只能加载通常的应用程序上下文内容:

代码语言:javascript
复制
@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开始,深入研究实现RequestDispatcherMockRequestDipatcher,以某种方式在那里添加一个过滤器,然后告诉GenericWebContextLoader使用我的实现……但我对整个web堆栈都很不熟悉,我更喜欢一种更简单的解决方案,它可以帮助我避免明显地挖掘那些东西……

有什么想法/解决方案吗?

我该如何手动添加过滤器呢?web.xml不可能是唯一这样做的地方...

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-06-14 17:42:25

也许你可以模仿一下过滤链。Spring中有一个class可以做到这一点。代码看起来像这样:

代码语言:javascript
复制
     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论坛线程。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10999631

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档