设置 MockMvc 和 Spring Security
Spring Security 的测试支持需要 spring-test-4.1.3.RELEASE 或更高版本。 |
要将 Spring Security 与 Spring MVC Test 一起使用,请将 Spring Security 的 FilterChainProxy
添加为 Filter
。您还需要添加 Spring Security 的 TestSecurityContextHolderPostProcessor
来支持 在带有注解的 Spring MVC Test 中以用户身份运行。为此,请使用 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 集成所需的所有初始设置 |