例如,我们可以使用我们在 Testing Method Security 中使用的相同设置和注释来测试 EnableReactiveMethodSecurity 中的示例。 以下最小示例显示了我们可以做什么:spring-doc.cn

@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()
    }
}