测试方法安全
例如,我们可以使用与我们在 测试方法安全 中使用的相同设置和注释来测试来自 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()
}
}