# 设置mockmvc和 Spring 安全性

为了使用 Spring 安全性与 Spring MVC测试，有必要将 Spring 安全性`FilterChainProxy`添加为`Filter`。还需要添加 Spring security的`TestSecurityContextHolderPostProcessor`以支持[Running as a User in Spring MVC Test with Annotations](#test-mockmvc-withmockuser)。这可以使用 Spring security的`SecurityMockMvcConfigurers.springSecurity()`来完成。例如：

|   |Spring 安全性的测试支持需要 Spring-test-4.1.3.release或更高版本。|
|---|--------------------------------------------------------------------------------|

Java

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

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SecurityConfig.class)
@WebAppConfiguration
public class CsrfShowcaseTests {

	@Autowired
	private WebApplicationContext context;

	private MockMvc mvc;

	@Before
	public void setup() {
		mvc = MockMvcBuilders
				.webAppContextSetup(context)
				.apply(springSecurity()) (1)
				.build();
	}

...
```

Kotlin

```
@RunWith(SpringJUnit4ClassRunner::class)
@ContextConfiguration(classes = [SecurityConfig::class])
@WebAppConfiguration
class CsrfShowcaseTests {

    @Autowired
    private lateinit var context: WebApplicationContext

    private var mvc: MockMvc? = null

    @Before
    fun setup() {
        mvc = MockMvcBuilders
            .webAppContextSetup(context)
            .apply<DefaultMockMvcBuilder>(springSecurity()) (1)
            .build()
    }
// ...
```

|**1**|`SecurityMockMvcConfigurers.springSecurity()`将执行将 Spring 安全性与 Spring MVC测试集成所需的所有初始设置|
|-----|---------------------------------------------------------------------------------------------------------------------------------------------|

[MockMVC支持](index.html)[安全请求后置处理器](request-post-processors.html)