使用Spring Mvc测试测试Spring Security Controller

登录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:预期状态:< 302>但是:< 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添加了官方Test Support.有一节详细介绍了testing with 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.

转载注明原文:使用Spring Mvc测试测试Spring Security Controller - 代码日志