模拟ReactiveSecurityContextHolder

时间:2018-09-17 12:34:57

标签: java mockito

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

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

2 个答案:

答案 0 :(得分:0)

要模拟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...
}

或者,您可以将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

中查找更多信息

答案 1 :(得分:-1)

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