繁体   English   中英

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

[英]Unit Testing /login in Spring MVC using 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);
}

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

但是我很不错,当我运行应用程序而不是测试时,用户到/login POST工作正常。 此外,当我尝试发出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/以获取灵感。

您可以使用spring安全测试类来测试基于表单的登录。 您需要执行以下操作来测试基于表单的登录。

Maven的依赖:

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <version>4.0.0.M1</version>
    <scope>test</scope>
</dependency>

<repositories>
    <repository>
        <id>spring-snasphot</id>
        <url>https://repo.spring.io/libs-snapshot</url>
    </repository>
</repositories>

测试类别:

import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;

RequestBuilder requestBuilder = formLogin().user("username").password("passowrd");
mockMvc.perform(requestBuilder)
    .andDo(print())
    .andExpect(status().isOk())
    .andExpect(cookie().exists("JSESSIONID"));

在这里关注我的帖子: Spring MockMvcBuilders安全过滤器

我已经设法使用UsernamePasswordAuthenticationToken为/ oauth / token创建REST API,但是我没有为受保护的资源创建测试(在运行的服务器上运行正常)。 您能告诉我们您的REST界面吗?

通过测试SpringSession,我实现了获取会话cookie并将会话保存到嵌入式Redis的目的:

@Autowired
private SessionRepositoryFilter<?> springSessionRepositoryFilter;
...

@Before
public void setup() {
    mvc = MockMvcBuilders
        .webAppContextSetup(context)
        .addFilters(springSessionRepositoryFilter)
        .apply(springSecurity())
        .build();
}

希望能帮助到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM