java 使用 Mockito 调用最终类静态方法的模拟对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17083432/
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-11-01 00:54:45  来源:igfitidea点击:

Mock objects calling final classes static methods with Mockito

javaunit-testingjunitmockito

提问by user962206

I just started mocking different layers of our application. I came to a point where one of my mock objects is returning NPE when it calls a final class static method. Is there a way around this?

我刚刚开始模拟我们应用程序的不同层。我的一个模拟对象在调用最终类静态方法时返回 NPE。有没有解决的办法?

e.g.

例如

when(mockObject.someMethod(FinalClass.staticMethod(someParam)).anotherMethodCall)
    .thenReturn("someString");

回答by DaveH

You have to use PowerMock and Mockito together.

您必须同时使用 PowerMock 和 Mockito。

I don't understand what your code snippet is trying to do, but the following snippets allow the static getInstance()method of the Calendarclass to return a mocked CalendarObject. Maybe that'll point you in the right direction

我不明白你的代码片段试图做什么,但以下片段允许类的静态getInstance()方法Calendar返回一个模拟Calendar对象。也许这会给你指明正确的方向

At the class level:

在班级层面:

@RunWith(PowerMockRunner.class)
@PrepareForTest(Calendar.class)
public class XXXXXX {

In your test method:

在您的测试方法中:

PowerMockito.mockStatic(Calendar.class);
    Calendar calendar = mock(Calendar.class);
    when(calendar.get(eq(Calendar.HOUR_OF_DAY))).thenReturn(3);

    Mockito.when(Calendar.getInstance()).thenReturn(calendar);

回答by anergy

Mockito doesn't support mocking a final class.Have a look at PowerMock.It allows you to mock static methods and classes. It can work with Mockito, documentationexplains how to do that.

Mockito 不支持模拟最终类。看看PowerMock 。它允许你模拟静态方法和类。它可以与 Mockito 一起使用,文档解释了如何做到这一点。