java PowerMock - 使用私有构造函数模拟单例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27108194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 11:14:49  来源:igfitidea点击:

PowerMock - Mock a Singleton with a Private Constructor

javaunit-testingsingletonpowermockeasymock

提问by Hyman

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

我正在使用 PowerMock 和 EasyMock,想知道如何使用私有构造函数模拟单例?

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 crazyServerStuffmethod?

我该如何模拟该crazyServerStuff方法?

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

但我得到了错误 java.lang.IllegalArgumentException: No visible constructors in class Singleton

Does anyone know what I'm missing?

有谁知道我错过了什么?

采纳答案by Hyman

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

可悲的是,我认为这对 Android 来说是不可能的 - 请参阅此答案

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

如果您不是在 Android 上,看起来就是您的操作方式。

回答by Pavel Lechev

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

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