我如何在测试中模拟 ReactiveSecurityContextHolder 以便有可能进入 lambda flatmap
ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication)
.flatMap(authentication -> {})
最佳答案
模拟 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...
}
或者,您可以使用
SpringRunner
与 @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...
}
在 https://docs.spring.io/spring-security/site/docs/current/reference/html/test.html 中查找更多信息
关于java - 模拟 ReactiveSecurityContextHolder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52367880/