【问题标题】:Spring MockMvc doesn't contain cookiesSpring MockMvc 不包含 cookie
【发布时间】:2018-03-29 08:40:59
【问题描述】:

我有一个受 HTTP Basic 身份验证保护的控制器。

我将应用设置为使用会话 cookie,它可以工作。

但是,当我使用 MockMvc 测试控制器时,成功的身份验证不会给我任何 cookie。

网页配置:

package world.pyb.spring.cookiesdemo;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;

@Configuration
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("admin").password("argentina").roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //@formatter:off
        http.httpBasic()
                .and().authorizeRequests().antMatchers(HttpMethod.GET, "/hello").authenticated()
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.ALWAYS);
        //@formatter:on
    }
}

简单的控制器:

package world.pyb.spring.cookiesdemo;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String index() {
        return "Greetings from Spring Boot!";
    }

}

不给我会话 cookie 的简单控制器测试:

package world.pyb.spring.cookiesdemo;

import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.cookie;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {

    @Autowired
    private MockMvc mvc;

    @Test
    public void getHello() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/hello")
            .with(SecurityMockMvcRequestPostProcessors.httpBasic("admin", "argentina"))
    )
        // prints "Cookies = []"
        .andDo(MockMvcResultHandlers.print())
        .andExpect(cookie().exists("JSESSIONID"))
        .andExpect(status().is2xxSuccessful())
        .andExpect(content().string(equalTo("Greetings from Spring Boot!")));
    }

}

相关问题:

一些答案​​建议不要使用 MockMvc,但如果可能,我想继续使用它。

【问题讨论】:

标签: spring-mvc testing cookies spring-security


【解决方案1】:

如问题代码所示,MockMvcResultMatcher 包含对 cookie 的支持。

只要被测控制器本身提供 cookie,就可以正常工作。这里的问题是 cookie 是由 Spring Security 提供的,它是控制器的包装器。 MockMvc 正在直接测试您的控制器,测试您在其真实 HTTP 服务器中运行的控制器,这是测试安全层 cookie 所必需的。

这就是为什么TestRestTemplate 会在其完整的服务器上下文中调用您的控制器,从而提供更全面的测试环境。

但请注意,从 Spring 5 开始,运行服务器 API 测试的新方法基于 WebTestClient

【讨论】:

猜你喜欢
  • 2014-11-26
  • 1970-01-01
  • 2014-01-01
  • 2019-11-02
  • 2016-11-30
  • 1970-01-01
  • 2018-01-14
  • 2016-02-05
  • 1970-01-01
相关资源
最近更新 更多