PowerMock - Mock a Singleton with a Private Constr

2019-07-20 17:33发布

问题:

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.