gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 02:13:54 25 4
gpt4 key购买 nike

因此,我们几乎已经达到了测试驱动我们的 spring web-mvc 应用程序的目标。我们正在使用 spring security 来保护 URL 或方法,我们想使用 Spring-Web-Mvc 来测试 Controller 。问题是:Spring security 依赖于 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 时会提示 annonymus 用户登录。这与 web.xml 一起工作正常,但我们不知道如何集成它进入我们的测试。

有没有办法给spring-test-mvc添加过滤器?

现在我想我可能必须从 GenericWebContextLoader 开始,深入研究实现 RequestDispatcherMockRequestDipatcher,添加一个过滤器不知何故然后告诉 GenericWebContextLoader 使用我的实现......但我对整个网络堆栈非常不熟悉并且更喜欢一个更简单的解决方案来帮助我避免深入研究这些东西......

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

无论如何,我将如何手动添加过滤器? web.xml 不能是唯一的地方...

谢谢!

最佳答案

也许您可以模拟过滤器链。有一个class在 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);

然后您可以将 org.springframework.web.filter.DelegatingFilterProxy 实例添加到链在你的代码中。像这样的东西:

另见 this论坛主题。

关于java - 使用 Spring-Test-MVC 对 Spring-Security 进行单元测试 - 集成 FilterChain/ServletFilter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10999631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com