此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Security 6.4.1! |
测试方法安全性
例如,我们可以使用我们在 Testing Method Security 中使用的相同设置和注释来测试 EnableReactiveMethodSecurity 中的示例。 以下最小示例显示了我们可以做什么:
-
Java
-
Kotlin
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = HelloWebfluxMethodApplication.class)
public class HelloWorldMessageServiceTests {
@Autowired
HelloWorldMessageService messages;
@Test
public void messagesWhenNotAuthenticatedThenDenied() {
StepVerifier.create(this.messages.findMessage())
.expectError(AccessDeniedException.class)
.verify();
}
@Test
@WithMockUser
public void messagesWhenUserThenDenied() {
StepVerifier.create(this.messages.findMessage())
.expectError(AccessDeniedException.class)
.verify();
}
@Test
@WithMockUser(roles = "ADMIN")
public void messagesWhenAdminThenOk() {
StepVerifier.create(this.messages.findMessage())
.expectNext("Hello World!")
.verifyComplete();
}
}
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = [HelloWebfluxMethodApplication::class])
class HelloWorldMessageServiceTests {
@Autowired
lateinit var messages: HelloWorldMessageService
@Test
fun messagesWhenNotAuthenticatedThenDenied() {
StepVerifier.create(messages.findMessage())
.expectError(AccessDeniedException::class.java)
.verify()
}
@Test
@WithMockUser
fun messagesWhenUserThenDenied() {
StepVerifier.create(messages.findMessage())
.expectError(AccessDeniedException::class.java)
.verify()
}
@Test
@WithMockUser(roles = ["ADMIN"])
fun messagesWhenAdminThenOk() {
StepVerifier.create(messages.findMessage())
.expectNext("Hello World!")
.verifyComplete()
}
}