我知道可以模拟单个枚举(使用 How to mock an enum singleton class using Mockito/Powermock? ),但我有 1000 个枚举值,它们可以调用 5 个不同的构造函数。枚举值在开发过程中经常发生变化。
我只想为我的 JUnit 测试模拟一两个。我不关心其余的,但它们仍然是实例化的,这会调用一些讨厌的东西,从文件系统加载枚举的值。
是的,我知道这是非常糟糕的设计。但现在我没有时间更改它。
目前我们正在使用 Mockito/powermock。但是任何可以解决这个问题的框架 sh** 我的意思是欢迎糟糕的设计。
假设我有一个与此类似的枚举:
public static enum MyEnum {
A(OtherEnum.CONSTANT),
B("1"),
C("1", OtherEnum.CONSTANT),
//...and so on for again 1000 enum values :(
private double value;
private String defaultValue;
private OtherEnum value;
/* Getter/Setter */
/* constructors */
}
最佳答案
我同意 Nick-Holt 建议添加接口(interface)的意见:
public interface myInterface{
//add the getters/setters you want to test
}
public enum MyEnum implements MyInterface{
//no changes needed to the implementations
//since they already implement the methods you want to use
}
现在您可以使用 Mockito 的正常模拟功能,而无需依赖 Powermock
MyInterface mock = Mockito.mock(MyInterface.class);
when(mock.foo()).thenReturn(...);
//..etc
关于java - JUnit 测试 : Suppress enum constructor by mocking?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22346396/