Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock ReactiveSecurityContextHolder

Tags:

java

mockito

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 -> {})
like image 923
Guseyn Ismayylov Avatar asked Jul 31 '26 13:07

Guseyn Ismayylov


1 Answers

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

like image 53
Evgeniy Khyst Avatar answered Aug 03 '26 04:08

Evgeniy Khyst



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!