PowerMock - Mock ein Singleton mit einem Privaten Konstruktor

Ich bin mit PowerMock mit EasyMock, und fragte mich, wie ich vielleicht verspotten ein singleton mit einem privaten Konstruktor?

Sagen wir mal ich hab folgende Klasse:

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

    public static Singleton getInstance() {
        return singleton;
    }

    public int crazyServerStuff() { ... }
}

Und eine Klasse, die verwendet diese:

public class Thing {
    public Thing() {}

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

Wie könnte ich verspotte die crazyServerStuff Methode?

Ich habe versucht, die folgenden:

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

        ...
    }
}

Aber ich bekomme die Fehlermeldung java.lang.IllegalArgumentException: No visible constructors in class Singleton

Weiß jemand was mir fehlt?

InformationsquelleAutor Jack | 2014-11-24
Schreibe einen Kommentar