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

时间:2015-10-22 05:20:21

标签: java unit-testing powermock 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;
    }
}

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

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方法。他们总是出现无效。

1 个答案:

答案 0 :(得分:2)

你需要做这样的事情。

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