Mock ReactiveSecurityContextHolder

Viewed 2106

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 -> {})
2 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

You just need to add @WithMockUser("customUserName") on test.

Related