[英]Mock Static Enum Inside Final Class
有一个X级;
public final class X {
private X() {}
...
public static enum E {
thingA("1"),
thingB("0")
public boolean isEnabled(){...}
}
...
}
在另一个类中,有一个方法M
public class AnotherClass{
public void M(){
if (E.thingB.isEnabled()) {
doSomething();
}
}
...
}
我想测试M方法,是否可以使用Mockito / PowerMockito在其中模拟语句。 做这样的事情
when(E.thingB.isEnabled()).thenReturn(true)?
无论枚举是否嵌套,都不能创建或模拟枚举的新实例。 枚举是隐式的final ,更重要的是,它打破了枚举的所有实例都在枚举中声明的假设。
枚举类型除了由其枚举常量定义的实例外,没有其他实例。 尝试显式实例化枚举类型是编译时错误。 ( JLS )
因为枚举的所有实例在编译时都是已知的,并且这些实例的所有属性同样是可预测的,所以通常您可以传入一个满足您需求的实例而无需模拟任何内容 。 如果要接受具有这些属性的任意实例,请让您的枚举实现一个接口。
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.