Java Mock ReactiveSecurityContextHolder

Java Mock ReactiveSecurityContextHolder,java,mockito,Java,Mockito,如何在测试中模拟ReactiveSecurityContextHolder,以便能够进入lambdaflatmap ReactiveSecurityContextHolder.getContext() .map(SecurityContext::getAuthentication) .flatMap(authentication -> {}) 您只需在测试中添加@WithMockUser(“customUserName”)。到Reactiv

如何在测试中模拟ReactiveSecurityContextHolder,以便能够进入lambda
flatmap

ReactiveSecurityContextHolder.getContext()
            .map(SecurityContext::getAuthentication)
            .flatMap(authentication -> {})

您只需在测试中添加
@WithMockUser(“customUserName”)

ReactiveSecurityContextHolder中持有的模拟
身份验证
,您需要使用:

或者,您可以将
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...
}
在中查找更多信息

@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...
}