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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28231336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:13:15  来源:igfitidea点击:

Unit Testing /login in Spring MVC using MockMvc

javaspringunit-testingspring-mvcmockmvc

提问by Volkan Yaz?c?

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

我有一个使用 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);
}

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

当我运行应用程序时,自定义控制器和登录/注销页面都可以正常工作。我甚至可以单元测试/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"));
}

it fails as follows:

它失败如下:

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>

But I am pretty user POSTto /loginis working when I run the application instead of test. Further, when I try make a GETor HEADrequest (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?

但是我非常用户POST/login当我运行应用程序,而不是测试的工作。此外,当我尝试 make a GETor HEADrequest(如Headers = {Allow=[HEAD, GET]}日志行中所建议的)时,这次我收到了 404。关于发生了什么以及如何修复它的任何想法?

回答by sodik

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

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

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

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.

可能需要一些额外的设置,您可以查看http://www.petrikainulainen.net/programming/spring-framework/integration-testing-of-spring-mvc-applications-security/以获得灵感。

回答by Mithun

You could use spring security testing classes to test form based login. You need to do the following to test form based login.

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

Maven dependency:

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>

Test class:

测试类:

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"));

回答by Pegazus

Following my post here: Spring MockMvcBuilders Security filter

关注我的帖子: Spring MockMvcBuilders Security filter

I have manage to create REST API with UsernamePasswordAuthenticationToken for /oauth/token but I didn't manage to create the test for my protected resource (on running server it work fine). Could you show us your REST interface ?

我已经设法使用 UsernamePasswordAuthenticationToken 为 /oauth/token 创建 REST API,但我没有设法为我的受保护资源创建测试(在运行的服务器上它工作正常)。你能向我们展示你的 REST 接口吗?

回答by jpadilladev

Testing SpringSession, I achieved to get the session cookie and saving session to an embedded Redis doing this:

测试 SpringSession,我实现了获取会话 cookie 并将会话保存到嵌入式 Redis 这样做:

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

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

Hope it helps.

希望能帮助到你。