我知道可以模拟单个枚举(使用如何使用 Mockito/Powermock 模拟枚举单例类? https://stackoverflow.com/questions/15939023/how-to-mock-an-enum-singleton-class-using-mockito-powermock),但我有大约 1000 个枚举值,它们可以调用 5 个不同的构造函数。枚举值在开发过程中经常发生变化。
我只想为我的 JUnit 测试模拟一两个。我不关心其余的,但它们仍然被实例化,这会调用一些讨厌的东西,从文件系统加载枚举的值。
是的,我知道这是非常糟糕的设计。但现在我还没有时间去改变它。
目前我们正在使用 Mockito/powermock。但是任何可以解决这个问题的框架我的意思是糟糕的设计都是受欢迎的。
假设我有一个与此类似的枚举:
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 的建议,他建议添加一个接口:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)