使用 PowerMockito 模拟 Singleton Public/Void 方法失败

Mocking of Singleton Public/Void method failing with PowerMockito

场景是这样的:

public class classA implements classRandom {
   public void methodA(arg1, arg2) {
       POJOb objB;
       objB = SingletonClass_Instance().singletonMethodA(arg1);
   }
   public SingletonClass SingletonClass_Instance() {
       return SingletonClass.getInstance();
   }
}

public class SingletonClass {
    public objB singletonMethodA(final String arg1) {
        return randomObj;
    }
}

我正在为 Class A 中的方法 A 编写单元测试。为此,我编写了以下存根代码:

SingletonClass mockSingletonClass = PowerMockito.mock(SingletonClass.class);
POJOb = PowerMockito.mock(POJOb.class);
Mockito.when(mockSingletonClass.singletonMethodA(Mockito.anyString())).thenReturn(POJOb);

紧接着这段代码,我有一个代码:

POJOb objB = classA_Object.methodA(arg1, arg2);

此代码一到达就失败:

**methodA -->  SingletonClass_Instance().singletonMethodA**

我已经使用了以下 Powermockito 程序:

1) import PM libs
2) Added @PrepareForTest({SingletonClass.class, POJOb.class})

我仍然无法模拟 SingletonClass 的 Public/Void 方法。他们总是出来是空的。

你需要做这样的事情。

PowerMockito.mockStatic(SingletonClass.class);
SingletonClass mockSingleton = PowerMockito.mock(SingletonClass.class);
PowerMockito.when(SingletonClass.getInstance()).thenReturn(mockSingleton);