Java 使用 mockito 模拟静态方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24655524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 13:50:12  来源:igfitidea点击:

Mock a static method with mockito

javaunit-testingmockingmockito

提问by Gábor Csikós

I want to mock a static method in Mockito.

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

As far as I know this is not possible, how can I get around the problem? powermock is not an option.

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

I want that my authentication variable won't be null.

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

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

I read an answer herebut I don't know how to put this answer to code. Can someone give a solution?

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

采纳答案by pgiecek

As you pointed out, it is not possible to mock static methods with Mockito and since you do not wanna use Powermock or other tools, you can try something as follows in your tests.

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

  1. Create test authentication object

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

  2. Mock security context

    SecurityContext context = mock(SecurityContext.class);

  3. Ensure your mock returns the respective authentication

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

  4. Set security context into holder

    SecurityContextHolder.setContext(securityContext);

  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);

Now every call to SecurityContextHolder.getContext().getAuthentication()should return authentication object created in step 1.

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