java - 使用 MockMvc 在 Spring MVC 中进行单元测试/登录

标签 java spring unit-testing spring-mvc mockmvc

我有一个使用 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 正在工作。此外,当我尝试发出 GETHEAD 请求时(如 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/

相关文章:

java - 无法在服务器上创建目录。权限问题?

Java:PrintStream 和 PrintWriter 之间的区别

java - 括号和数组声明的问题

java - 测试 Java 方法是否同步的好方法是什么?

Node.js sinon 在并行执行中 stub 函数导致测试失败

java - 用于打开 TIFF(类型 4)图像的 Eclipse 扩展?

java - Spring MVC + Spring Security + JPA 返回 Null ModelAndView 并且不会进行身份验证

spring - Spring Boot 中用于模块化应用程序的插件系统

java - Spring Boot 不识别其余存储库

python - 从 python 混合器接收空值