模拟对象使用Mockito调用final类静态方法

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

例如

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

你必须一起使用PowerMock和Mockito。

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

在class级:

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

在你的测试方法中

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

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