使用 mockito 模拟静态方法

Gáb*_*kós 5 java unit-testing mocking mockito

我想在 Mockito 中模拟一个静态方法。

据我所知这是不可能的,我该如何解决这个问题?powermock 不是一个选项。

我希望我的身份验证变量不会为空。

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Run Code Online (Sandbox Code Playgroud)

在这里阅读了一个答案但我不知道如何将此答案写入代码。有人可以给出解决方案吗?

pgi*_*cek 10

正如您所指出的,使用 Mockito 模拟静态方法是不可能的,并且由于您不想使用 Powermock 或其他工具,您可以在测试中尝试以下操作。

  1. 创建测试认证对象

    Authentication auth = new ... // create instance based on your needs and with required attributes or just mock it if you do not care

  2. 模拟安全上下文

    SecurityContext context = mock(SecurityContext.class);

  3. 确保您的模拟返回相应的身份验证

    when(context.getAuthentication()).thenReturn(auth);

  4. 将安全上下文设置为持有者

    SecurityContextHolder.setContext(securityContext);

现在每次调用都SecurityContextHolder.getContext().getAuthentication()应该返回在步骤 1 中创建的身份验证对象。