servlet-test-mockmvc-setup.md 1.9 KB
Newer Older
茶陵後's avatar
茶陵後 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
# Setting Up MockMvc and Spring Security

In order to use Spring Security with Spring MVC Test it is necessary to add the Spring Security `FilterChainProxy` as a `Filter`.
It is also necessary to add Spring Security’s `TestSecurityContextHolderPostProcessor` to support [Running as a User in Spring MVC Test with Annotations](#test-mockmvc-withmockuser).
This can be done using Spring Security’s `SecurityMockMvcConfigurers.springSecurity()`.
For example:

|   |Spring Security’s testing support requires spring-test-4.1.3.RELEASE or greater.|
|---|--------------------------------------------------------------------------------|

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()` will perform all of the initial setup we need to integrate Spring Security with Spring MVC Test|
|-----|---------------------------------------------------------------------------------------------------------------------------------------------|

[MockMvc Support](index.html)[Security RequestPostProcessors](request-post-processors.html)