配置MockMvc和Spring Security
Spring Security的测试支持需要spring-test 4.1.3.RELEASE或更高版本。 |
要在Spring MVC Test中使用Spring Security,请添加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集成所需的所有初始设置 |