how can I mock ReactiveSecurityContextHolder in the tests so it will be possible to get into the lambda flatmap
ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication)
.flatMap(authentication -> {})
To mock Authentication held in the ReactiveSecurityContextHolder you need to use TestSecurityContextHolder and 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...
}
Alternatively, you can use SpringRunner with @TestExecutionListeners annotation instead of 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...
}
Find more information in the https://docs.spring.io/spring-security/site/docs/current/reference/html/test.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With