使用MockMvc在Spring MVC中进行单元测试/登录 [英] Unit Testing /login in Spring MVC using MockMvc

查看:452
本文介绍了使用MockMvc在Spring MVC中进行单元测试/登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用Spring MVC创建的非常简单的REST应用程序. (可在 GitHub 上找到代码.)它具有简单的

I have a very simple REST application created using Spring MVC. (Code is available at GitHub.) It has a simple WebSecurityConfigurer as follows:

@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);
}

当我运行该应用程序时,自定义控制器和登录/注销页面都可以正常工作.我什至可以单元测试 /user/new通过MockMvc.但是,当我尝试使用以下功能测试/login

When I run the application, both the custom controllers and the login/logout pages work without a problem. I can even unit test /user/new via MockMvc. However, when I try to test /login with the following function

@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.有关正在发生的事情以及如何解决它的任何想法?

But I am pretty user POST to /login is working when I run the application instead of test. Further, when I try make a GET or HEAD request (as suggested in the Headers = {Allow=[HEAD, GET]} line of the logs), this time I receive a 404. Any ideas about what is going on and how can I fix it?

推荐答案

我现在注意到github链接.我相信您还需要为测试配置安全过滤器.像

I noticed the github link now. I believe you need to configure security filter also for your tests. Something like

 mockMvc = MockMvcBuilders.webApplicationContextSetup(webApplicationContext)
                .addFilter(springSecurityFilterChain)
                .build();

可能需要一些其他设置,您可以检查 http://www.petrikainulainen.net/programming/spring-framework/integration-testing-of-spring-mvc-applications-security/以获得启发.

Some additional settings might be necessary, you might check http://www.petrikainulainen.net/programming/spring-framework/integration-testing-of-spring-mvc-applications-security/ for inspiration.

这篇关于使用MockMvc在Spring MVC中进行单元测试/登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆