Setting Up MockMvc and Spring Security

Spring Security 的测试支持需要 spring-test-4.1.3.RELEASE 或更高版本。

要将 Spring Security 与 Spring MVC Test 结合使用,请添加 Spring Security FilterChainProxy`作为 `Filter。您还需要添加 Spring Security 的 TestSecurityContextHolderPostProcessor`以支持 Running as a User in Spring MVC Test with Annotations。为此,请使用 Spring Security 的 `SecurityMockMvcConfigurers.springSecurity()

  • Java

  • Kotlin

import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*;

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = SecurityConfig.class)
@WebAppConfiguration
public class CsrfShowcaseTests {

	@Autowired
	private WebApplicationContext context;

	private MockMvc mvc;

	@BeforeEach
	public void setup() {
		mvc = MockMvcBuilders
				.webAppContextSetup(context)
				.apply(springSecurity()) (1)
				.build();
	}
	// ...
}
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = [SecurityConfig::class])
@WebAppConfiguration
class CsrfShowcaseTests {

    @Autowired
    private lateinit var context: WebApplicationContext

    private var mvc: MockMvc? = null

    @BeforeEach
    fun setup() {
        mvc = MockMvcBuilders
            .webAppContextSetup(context)
            .apply<DefaultMockMvcBuilder>(springSecurity()) (1)
            .build()
    }
    // ...
}
1 SecurityMockMvcConfigurers.springSecurity() 将执行我们集成 Spring Security 与 Spring MVC Test 所需的所有初始设置