我有一个使用 Spring MVC 创建的非常简单的 REST 应用程序。 (代码可在 GitHub 获得。)它有一个简单的 WebSecurityConfigurer
。如下:
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.authorizeRequests()
.antMatchers("/user/new").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login").permitAll()
.successHandler(authenticationSuccessHandler)
.failureHandler(authenticationFailureHandler)
.and()
.logout()
.permitAll()
.logoutSuccessHandler(logoutSuccessHandler);
}
当我运行应用程序时,自定义 Controller 和登录/注销页面都可以正常工作。我什至可以unit test /user/new
通过 MockMvc
。但是,当我尝试使用以下函数测试 /login
时
@Test
public void testUserLogin() throws Exception {
RequestBuilder requestBuilder = post("/login")
.param("username", testUser.getUsername())
.param("password", testUser.getPassword());
mockMvc.perform(requestBuilder)
.andDo(print())
.andExpect(status().isOk())
.andExpect(cookie().exists("JSESSIONID"));
}
失败如下:
MockHttpServletRequest:
HTTP Method = POST
Request URI = /login
Parameters = {username=[test-user-UserControllerTest], password=[test-user-UserControllerTest-password]}
Headers = {}
Handler:
Type = org.springframework.web.servlet.resource.ResourceHttpRequestHandler
Async:
Was async started = false
Async result = null
Resolved Exception:
Type = org.springframework.web.HttpRequestMethodNotSupportedException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
MockHttpServletResponse:
Status = 405
Error message = Request method 'POST' not supported
Headers = {Allow=[HEAD, GET]}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: Status expected:<200> but was:<405>
但是当我运行应用程序而不是测试时,我很高兴 POST
到 /login
正在工作。此外,当我尝试发出 GET
或 HEAD
请求时(如 Headers = {Allow=[HEAD, GET]}
行中所建议日志),这次我收到了 404。关于发生了什么以及如何解决它有什么想法吗?
最佳答案
我现在注意到了 github 链接。我相信您还需要为您的测试配置安全过滤器。有点像
mockMvc = MockMvcBuilders.webApplicationContextSetup(webApplicationContext)
.addFilter(springSecurityFilterChain)
.build();
可能需要一些额外的设置,您可以查看 http://www.petrikainulainen.net/programming/spring-framework/integration-testing-of-spring-mvc-applications-security/寻找灵感。
关于java - 使用 MockMvc 在 Spring MVC 中进行单元测试/登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28231336/