PowerMock-模拟具有私有构造函数的单例 [英] PowerMock - Mock a Singleton with a Private Constructor
本文介绍了PowerMock-模拟具有私有构造函数的单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将PowerMock与EasyMock一起使用,想知道如何用私有构造函数模拟单例吗?
I'm using PowerMock with EasyMock, and wondered how I might mock a singleton with a private constructor?
假设我有以下课程:
public class Singleton {
private static Singleton singleton = new Singleton();
private Singleton() { }
public static Singleton getInstance() {
return singleton;
}
public int crazyServerStuff() { ... }
}
和使用该类的类:
public class Thing {
public Thing() {}
public int doStuff(Singleton s) {
return s.crazyServerStuff() + 42;
}
}
我怎么嘲笑 crazyServerStuff
方法?
我尝试了以下操作:
@RunWith(PowerMockRunner.class)
@PrepareForTest(Singleton.class)
public class ThingTest extends AndroidTestCase {
@Test
public void testDoStuff() {
MemberModifier.suppress(MemberModifier.constructor(Singleton.class));
Singleton mockSingleton = PowerMock.createMock(Singleton.class);
...
}
}
但我收到错误 java.lang.IllegalArgumentException:类Singleton中没有可见的构造函数
有人知道我吗
推荐答案
可悲的是,我认为Android不可能做到这一点-请参见此答案。
Sadly I don't think this is possible for Android - see this answer.
如果您未使用Android,则其外观为这是您的操作方式。
If you're not on Android, it looks like this is how you do it.
这篇关于PowerMock-模拟具有私有构造函数的单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文