gpt4 book ai didi

java - 模拟 ReactiveSecurityContextHolder

转载 作者:行者123 更新时间:2023-12-04 01:52:25 26 4
gpt4 key购买 nike

我如何在测试中模拟 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com