[英]Testing Spring Security Controller Using Spring Mvc Test
登录jsp表单和spring security xml配置如下:
<spring:url value="/j_spring_security_check" var="login" />
<form action="${login}" method="POST">
<fieldset>
<legend>Login</legend>
<input type="text" name="j_username" id="username" placeholder="Usename"/>
<input type="text" name="j_password" id="password" placeholder="Password"/>
<input type="submit" value="Login" />
</fieldset>
</form>
...
<security:form-login login-page="/public/authentication/login.htm"
login-processing-url="/j_spring_security_check"
default-target-url="/public/index.htm"
authentication-failure-url="/public/authentication/login.htm?authenticationNok=1"/>
这是形式总结的测试:
@Test
public void testLoginPostController() throws Exception {
Account account = new AccountBuilder("test", "test", "test@gmail.com", Address.FAKE_EMPTY_ADDRESS4TESTS)
.build();
this.mockMvc.perform(post("/j_spring_security_check").param("j_username", account.getUsername()).param("j_password", "test"))
.andDo(print())
.andExpect(status().isMovedTemporarily())
.andExpect(view().name("redirect:/public/index.htm"));
}
但我得到: java.lang.AssertionError: Status expected:<302> but was:<404>
当我在浏览器中打开登录页面时,我看到生成的表单是:
<form action="/SpringMvcExample/j_spring_security_check" method="POST">
好的,我试着改变测试:
this.mockMvc.perform(post("/SpringMvcExample/j_spring_security_check").param("j_username", account.getUsername()).param("j_password", "test"))
但得到了相同的结果。 同时,当我在浏览器中提交登录表单时,它会将我重定向到public/index.htm
页面,作为test中的exptect。
我究竟做错了什么?
更新 :Spring Security 4增加了官方测试支持 。 有一节介绍了MockMvc的详细测试 。
听起来好像你还没有将Spring Security Filter添加到你的MockMvc中。 例如:
public class MyTests {
@Autowired
private FilterChainProxy springSecurityFilterChain;
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webApplicationContextSetup(this.wac)
.addFilters(this.springSecurityFilterChain).build();
}
@Test
public void testLoginPostController() throws Exception {
Account account = new AccountBuilder("test", "test", "test@gmail.com", Address.FAKE_EMPTY_ADDRESS4TESTS)
.build();
this.mockMvc.perform(post("/j_spring_security_check").param("j_username", account.getUsername()).param("j_password", "test"))
.andDo(print())
.andExpect(status().isMovedTemporarily())
.andExpect(view().name("redirect:/public/index.htm"));
}
}
发生这种情况的原因是因为现在MockMvc只知道你的Spring MVC配置并且不知道任何Filter(即FilterChainProxy)。 由于用户名和密码的验证(即/ j_spring_security_check的处理)在FilterChainProxy中发送之前发送到Spring MVC并且您没有包含它,因此您获得了404。
/j_spring_security_check
是Spring Security处理的一个特殊地址(可能通过其过滤器,但我没有验证这一点)。 它不是在Spring MVC中注册的请求处理程序,因此您无法使用MockMVC对其进行测试。
您需要启动一个真正的应用程序容器并使用HttpClient或Selenium。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.