简体   繁体   English

在最终课程中模拟静态枚举

[英]Mock Static Enum Inside Final Class

there is a class X; 有一个X级;

public final class X {
    private X() {}
    ...
    public static enum E {
        thingA("1"),
        thingB("0")

        public boolean isEnabled(){...}
    }
    ...
}

in some another class there a method M 在另一个类中,有一个方法M

public class AnotherClass{

    public void M(){
        if (E.thingB.isEnabled()) {
            doSomething();
        }
    }
    ...
}

i want to test M method, is it possible to use mockito/powermockito to mock statement within if. 我想测试M方法,是否可以使用Mockito / PowerMockito在其中模拟语句。 to do something like this 做这样的事情

 when(E.thingB.isEnabled()).thenReturn(true)?

Regardless of whether the enum is nested or not, you can't create or mock a new instance of an enum. 无论枚举是否嵌套,都不能创建或模拟枚举的新实例。 Enums are implicitly final , and more importantly, it breaks the assumption that all instances of the enum are declared within the enum. 枚举是隐式的final ,更重要的是,它打破了枚举的所有实例都在枚举中声明的假设。

An enum type has no instances other than those defined by its enum constants. 枚举类型除了由其枚举常量定义的实例外,没有其他实例。 It is a compile-time error to attempt to explicitly instantiate an enum type. 尝试显式实例化枚举类型是编译时错误。 ( JLS ) JLS

Because all instances of the enum are known at compile time, and all properties of those instances are likewise predictable, usually you can just pass in an instance that matches your needs without mocking anything . 因为枚举的所有实例在编译时都是已知的,并且这些实例的所有属性同样是可预测的,所以通常您可以传入一个满足您需求的实例而无需模拟任何内容 If you want to accept an arbitrary instance with those properties, have your enum implement an interface instead. 如果要接受具有这些属性的任意实例,请让您的枚举实现一个接口。

public interface I {
    boolean isEnabled();
}

public enum E implements I {  // By the way, all enums are necessarily static.
    thingA("1"),
    thingB("0");

    public boolean isEnabled(){...}
}

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

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