PowerMock - Mock a Singleton with a Private Constructor

此生再无相见时 提交于 2019-12-10 22:42:32

问题


I'm using PowerMock with EasyMock, and wondered how I might mock a singleton with a private constructor?

Let's say I have the following class:

public class Singleton {
    private static Singleton singleton = new Singleton();
    private Singleton() { }

    public static Singleton getInstance() {
        return singleton;
    }

    public int crazyServerStuff() { ... }
}

And a class which uses this:

public class Thing {
    public Thing() {}

    public int doStuff(Singleton s) {
        return s.crazyServerStuff() + 42;
    }
}

How might I mock the crazyServerStuff method?

I've tried the following:

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

        ...
    }
}

But I get the error java.lang.IllegalArgumentException: No visible constructors in class Singleton

Does anyone know what I'm missing?


回答1:


I don't think you should suppress the constructor, but rather mock it:

PowerMock.expectNew(Singleton.class).andReturn(mockObject)

https://code.google.com/p/powermock/wiki/MockConstructor




回答2:


Sadly I don't think this is possible for Android - see this answer.

If you're not on Android, it looks like this is how you do it.



来源:https://stackoverflow.com/questions/27108194/powermock-mock-a-singleton-with-a-private-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!