模拟 ReactiveSecurityContextHolder

Gus*_*lov 3 java mockito

我如何在测试中模拟 ReactiveSecurityContextHolder 以便有可能进入 lambda flatmap

ReactiveSecurityContextHolder.getContext()
            .map(SecurityContext::getAuthentication)
            .flatMap(authentication -> {})
Run Code Online (Sandbox Code Playgroud)

Evg*_*yst 7

嘲笑Authentication的召开ReactiveSecurityContextHolder需要使用TestSecurityContextHolderReactorContextTestExecutionListener

@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...
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用SpringRunnerwith@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...
}
Run Code Online (Sandbox Code Playgroud)

https://docs.spring.io/spring-security/site/docs/current/reference/html/test.html 中查找更多信息


Gus*_*lov -3

您只需要添加@WithMockUser("customUserName")测试即可。