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
Mock a static method with mockito
提问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 或其他工具,您可以在测试中尝试以下操作。
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
Mock security context
SecurityContext context = mock(SecurityContext.class);
Ensure your mock returns the respective authentication
when(context.getAuthentication()).thenReturn(auth);
Set security context into holder
SecurityContextHolder.setContext(securityContext);
创建测试认证对象
Authentication auth = new ... // create instance based on your needs and with required attributes or just mock it if you do not care
模拟安全上下文
SecurityContext context = mock(SecurityContext.class);
确保您的模拟返回相应的身份验证
when(context.getAuthentication()).thenReturn(auth);
将安全上下文设置为持有者
SecurityContextHolder.setContext(securityContext);
Now every call to SecurityContextHolder.getContext().getAuthentication()
should return authentication object created in step 1.
现在每次调用都SecurityContextHolder.getContext().getAuthentication()
应该返回在步骤 1 中创建的身份验证对象。