java - 模拟 ReactiveSecurityContextHolder

标签 java mockito

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

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

最佳答案

模拟 Authentication举办于ReactiveSecurityContextHolder您需要使用 TestSecurityContextHolder 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...
}

或者,您可以使用 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...
}

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

关于java - 模拟 ReactiveSecurityContextHolder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52367880/

相关文章:

java - java中字符串是如何传入方法的(就内存而言)

java - Junit - Spring 启动 : @Value is always null while testing

java - 使用现有 boolean 列类型的房间迁移

java - HBase Java Client批处理/放入CDH 4.6的速度很慢

java.io.EOFException(关闭流时出现问题)

java - Powermock - 模拟 super 方法调用

java - spring 注入(inject)模拟未使用

java.lang.IllegalStateException : Could not load CacheAwareContextLoaderDelegate unit test spring [Java]

java - Mockito 注解和方法调用的区别

java - 无法找到或加载主类org.apache.hadoop.hbase.util.HBaseConfTool