我如何在测试中模拟 ReactiveSecurityContextHolder 以便有可能进入 lambda flatmap
ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication)
.flatMap(authentication -> {})
Run Code Online (Sandbox Code Playgroud)
嘲笑Authentication的召开ReactiveSecurityContextHolder需要使用TestSecurityContextHolder和ReactorContextTestExecutionListener:
@RunWith(MockitoJUnitRunner.class)
public class ReactiveSecurityContextHolderTests {
@Mock
private Authentication authentication;
private TestExecutionListener reactorContextTestExecutionListener =
new ReactorContextTestExecutionListener();
@Before
public void setUp() throws Exception {
when(authentication.getPrincipal()).thenReturn("token");
TestSecurityContextHolder.setAuthentication(authentication);
reactorContextTestExecutionListener.beforeTestMethod(null);
}
@After
public void tearDown() throws Exception {
reactorContextTestExecutionListener.afterTestMethod(null);
}
//...tests...
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用SpringRunnerwith@TestExecutionListeners注释而不是MockitoJUnitRunner:
@RunWith(SpringRunner.class)
@TestExecutionListeners(ReactorContextTestExecutionListener.class)
public class ReactiveSecurityContextHolderTests {
private static Authentication authentication;
@BeforeClass
public static void setUp() throws Exception {
authentication = mock(Authentication.class);
when(authentication.getPrincipal()).thenReturn("token");
TestSecurityContextHolder.setAuthentication(authentication);
}
//...tests...
}
Run Code Online (Sandbox Code Playgroud)
在https://docs.spring.io/spring-security/site/docs/current/reference/html/test.html 中查找更多信息