使用Spring Mvc测试测试Spring Security Controller

 没有1200 发布于 2023-02-12 18:50

登录jsp表单和spring security xml配置如下:


Login
...

这是形式总结的测试:

@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>

当我在浏览器中打开登录页面时,我看到生成的表单是:

好的,我试着改变测试:

this.mockMvc.perform(post("/SpringMvcExample/j_spring_security_check").param("j_username", account.getUsername()).param("j_password", "test"))

但得到了相同的结果.同时,当我在浏览器中提交登录表单时,它会将我重定向到public/index.htm页面,如测试中的exptect.

我究竟做错了什么?

1 个回答
  • 更新: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.

    2023-02-12 18:54 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有