我如何在测试中模拟ReactiveSecurityContextHolder,以便有可能进入lambda flatmap
ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication)
.flatMap(authentication -> {})
答案 0 :(得分:0)
要模拟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
中查找更多信息答案 1 :(得分:-1)
您只需在测试中添加@WithMockUser("customUserName")
。