当前位置: 首页 > 知识库问答 >
问题:

如果禁用authorizarion,如何在测试中模拟安全上下文

能远
2023-03-14

我有这样的测试:

@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() {
   ...

共有1个答案

谷梁宝
2023-03-14

您可以模拟Spring的身份验证:

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"
    // ...
}
 类似资料:
  • 我们在Spring boot rest api中有下面的代码片段来获取用户角色。 我们在一个测试课上有这个。 但junit测试用例失败了。请建议如何为安全上下文持有者编写junit测试用例(针对上述代码)。

  • 我试图弄清楚如何进行单元测试,如果我的控制器的URL是正确的安全的。以防万一有人改变了周围的东西,不小心移除了安全设置。 我的controller方法如下所示: 我设置了一个WebTestEnvironment,如下所示: null 然而,如果仔细观察,这只在不向URL发送实际请求时才有帮助,而只在功能级别上测试服务时才有帮助。在我的案例中,抛出了“拒绝访问”异常: 以下两条日志消息值得注意,基本

  • 问题内容: 说我有一个包含以下内容的模块: 我想为下半部分编写一个单元测试(我想实现100%的覆盖率)。我发现执行导入/设置机制的内置的 runpy 模块,但无法弄清楚如何模拟或检查 main() 函数是否被调用。 到目前为止,这是我尝试过的: 问题答案: 我将选择另一种替代方法,将其从覆盖率报告中排除,当然,只有在测试中已经具有main()函数的测试用例的情况下,您才能这样做。 至于为什么我选择

  • 所以我第一次在spring boot测试时遇到了一个问题。当我执行测试时,这些值实际上被删除了。我更愿意对此进行模拟,这样这些值就不会被删除。 我的测试类:@SpringBootTest@AutoConfiguremockMVC

  • 我试图测试我的Spring MVC控制器,但我不断收到与Thymeleaf模板相关的错误。我真的不想在控制器测试中处理模板错误,因为这不是我真正感兴趣的。当模板不存在时让测试失败是可以的,但现在我收到了与根据错误代码找不到消息相关的错误。 当我运行应用程序时,这个问题不存在。我一直在尝试弄清楚如何设置测试环境来解决这个问题,但在那里我找不到任何有效的方法。现在,我只是真的想让控制器代码正常工作。