设置 MockMvc 和 Spring Security性
Spring Security 的测试支持需要spring-test-4.1.3.RELEASE或更高版本。 |
要将 Spring Security 与 Spring MVC Test 结合使用,请将 Spring Security 添加为 .
您还需要添加 Spring Security 以支持在带有注释的 Spring MVC 测试中以用户身份运行。
为此,请使用 Spring Security 的:FilterChainProxy
Filter
TestSecurityContextHolderPostProcessor
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 lateinit var mvc: MockMvc
@BeforeEach
fun setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply<DefaultMockMvcBuilder>(springSecurity()) (1)
.build()
}
// ...
}
1 | SecurityMockMvcConfigurers.springSecurity() 将执行我们将 Spring Security 与 Spring MVC Test 集成所需的所有初始设置 |