您可以使用spring-security-test
来实现这一点。
pom.xml
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>5.3.3.RELEASE</version>
<scope>test</scope>
</dependency>
假设您的控制器看起来像:
@PreAuthorize("hasRole('ROLE_ADMIN')")
public User createUser(final User user) {
......
}
您的测试可能如下所示:
public class MyControllerTests {
private MockMvc mvc;
@BeforeEach
void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
@Test
void testCreateWithProperPermission() throws Exception {
final User user = new User();
user.setName("Test");
final MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post("/v1/foo/").with(user("foo").roles("ADMIN"))
.content(new ObjectMapper().writeValueAsString(user))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
final String responseBody = mvcResult.getResponse().getContentAsString();
final User created = new ObjectMapper().readValue(responseBody, User.class);
// verify the saved entity's data is correct
assertThat(created).isNotNull();
assertThat(created)
.hasFieldOrPropertyWithValue("name", user.getName());
}