gpt4 book ai didi

java - 如果我禁用授权,如何在测试中模拟安全上下文

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:39:19 26 4
gpt4 key购买 nike

我有这样的测试:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
@ActiveProfiles("test")
public class MyTests {

@Autowired
private TestRestTemplate restTemplate;
....

在测试中我禁用了身份验证/授权

但在代码中我使用以下内容:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

但这是测试失败的原因。

我如何模拟我的测试?

附言

这个不行:

@Test
public void testUpdateWithoutNameAndEmail() {
Authentication authentication = Mockito.mock(Authentication.class);
SecurityContext securityContext = Mockito.mock(SecurityContext.class);
Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
SecurityContextHolder.setContext(securityContext);
Mockito.when(authentication.getName()).thenReturn("aName");

restTemplate.exchange(..

SecurityContextHolder.getContext().getAuthentication() 在代码中返回 null

还有这个:

@Autowired
private TestRestTemplate restTemplate;
@Test
@WithMockUser(username = "aUser", roles = { "ADMIN" })
public void testUpdateWithoutNameAndEmail() {
...

最佳答案

你可以模拟Spring的Authentication:

Authentication authentication = Mockito.mock(Authentication.class);

并告诉 Spring 的 SecurityContextHolder 存储这个 Authentication 实例:

SecurityContext securityContext = Mockito.mock(SecurityContext.class);
Mockito.when(securityContext.getAuthentication()).thenReturn(auth);
SecurityContextHolder.setContext(securityContext);

现在,如果您的代码需要 Authentication 来返回某些内容(可能是用户名),您只需以通常的方式对模拟的 Authentication 实例设置一些期望,例如

Mockito.when(authentication.getName()).thenReturn("aName");

还有一个 Spring 测试注释 (org.springframework.security.test.context.support.WithMockUser) 可以为您完成此操作...

@Test
@WithMockUser(username = "aUser", roles = { "anAuthority" })
public void aTest(){
// any usage of `Authentication` in this test will get an instance withe the user name "aUser" and a granted authority "anAuthority"
// ...
}

关于java - 如果我禁用授权,如何在测试中模拟安全上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46154235/

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