java 使用 PowerMockito 模拟单身人士

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37021702/
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-03 02:06:53  来源:igfitidea点击:

Mocking singleton with PowerMockito

javatestingmockitojunit4powermock

提问by Biologeek

in order to test one of the private method I coded, I need to mock a Singleton.

为了测试我编码的私有方法之一,我需要模拟一个单例。

After testing several methods with PowerMockito :

在使用 PowerMockito 测试了几种方法之后:

PowerMockito.mockStatic(UtilDatabaseSoldeAutoCdeCommon.class);
Mockito.when(UtilDatabaseSoldeAutoCdeCommon.getInstance()).thenReturn(mockDatabase);

I could never mock this class. Thus I cannot test my methods as in every of them, I access to database.

我永远无法嘲笑这门课。因此,我无法像在每个方法中一样测试我的方法,我访问数据库。

UtilDatabaseSoldeAutoCdeCommon is defined as such :

UtilDatabaseSoldeAutoCdeCommon 定义如下:

public class UtilDatabaseSoldeAutoCdeCommon extends AbstractUtilDatabase {

private static UtilDatabaseSoldeAutoCdeCommon instance;

private UtilDatabaseSoldeAutoCdeCommon() {
    super();
}

public static UtilDatabaseSoldeAutoCdeCommon getInstance() {
    if(instance == null) {
        instance = new UtilDatabaseSoldeAutoCdeCommon();
    }
    return instance;
}

...
}

I debugged powermockito when it calls getInstance() but everytime consructor is called, it crashes as it tries to load configuration file (which does not exist).

我在调用 getInstance() 时调试了 powermockito,但是每次调用构造函数时,它都会在尝试加载配置文件(不存在)时崩溃。

I precise that config file is defined as a constant in absract parent class of UtilDatabaseEnrichissement and used in constructor.

我确切地说,配置文件被定义为 UtilDatabaseEnrichissement 的抽象父类中的常量,并在构造函数中使用。

How could I test this part ?

我怎么能测试这部分?

回答by asch

I think this should work:

我认为这应该有效:

    @PrepareForTest({UtilDatabaseSoldeAutoCdeCommon.class})
    public class SomeTest {
        @Mock
        UtilDatabaseSoldeAutoCdeCommon fakeSingletonInstance;   

        @Test
        public void test() {
             Whitebox.setInternalState(UtilDatabaseSoldeAutoCdeCommon.class, "instance", fakeSingletonInstance);
             // Write here your test
        }
    }

回答by Mahesh

This question was asked long time back and I was facing similar issue and unable to find good answers hence answering it now. I tested the class with suppressing constructor like

这个问题很久以前就被问到了,我面临着类似的问题,无法找到好的答案,因此现在回答。我用抑制构造函数测试了类

PowerMockito.suppress(UtilDatabaseSoldeAutoCdeCommon.class.getConstructors());

PowerMockito.suppress(UtilDatabaseSoldeAutoCdeCommon.class.getConstructors());

回答by Slava Shpitalny

PrepareForTest the singleton class you mock

PrepareForTest 你模拟的单例类