简体   繁体   English

使用Powermock模拟枚举

[英]Mock enum instantiation using powermock

I have following code to test: 我有以下代码要测试:

Public MyClass() {

    public static final boolean myFunc(int param1, String param2, long param3) {

        SomeInterface var1 = SomeEnumImplementingSomeInterface.INSTANCE;
        SomeOtherInterface var2 = var1.getInstanceOfSomeOtherInterface();

        String str = var2.getValue();

        if (str.equals("ABCD"))
            return true;
        else 
            return false;
    }
}

Is there any way by which I can assign a mocked object to var1 here? 有什么办法可以在此处将模拟对象分配给var1?

One way around to this I could think of is declare var1 as class variable (it has to be static in this case since the method accessing it is static), and then assign mocked object to it by whiteboxing. 我能想到的一种解决方法是将var1声明为类变量(在这种情况下它必须是静态的,因为访问它的方法是静态的),然后通过白盒将模拟对象分配给它。 But I don't want to change the design just for the sake of testing it. 但是我不想为了测试而更改设计。

Please avoid suggesting me a change in the class design. 请避免建议我改变班级设计。

You could use a package or protected method to set var1 value, and in your test, if necessary, you can override your class to set the mock object, similar to this: 您可以使用包或受保护的方法来设置var1值,并且在测试中,如有必要,可以覆盖类以设置模拟对象,类似于以下内容:

public MyClass() {

    public static final boolean myFunc(int param1, String param2, long param3) {

        SomeInterface var1 = getVar1();
        SomeOtherInterface var2 = var1.getInstanceOfSomeOtherInterface();

        String str = var2.getValue();

        if (str.equals("ABCD"))
            return true;
        else 
            return false;
    }

    SomeInterface getVar1() {
        return SomeEnumImplementingSomeInterface.INSTANCE;
    }
}

public MyClassTest {

    private MyClass myClassUnderTest = new MyClass() {
        @Override
        SomeInterface getVar1() {
            return SomeEnumImplementingSomeInterface.INSTANCE;
        }
    } 

    public void testMyFunc() {
        // do test stuff with myClassUnderTest
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM