JUnit测试:通过模拟来抑制枚举构造函数?

kei*_*iki 7 java junit enums suppression mocking

我知道可以模拟单个枚举(使用如何使用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 */
}
Run Code Online (Sandbox Code Playgroud)

dka*_*zel 1

我同意 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

}
Run Code Online (Sandbox Code Playgroud)

现在您可以使用 Mockito 的正常模拟功能,而无需依赖 Powermock

MyInterface mock = Mockito.mock(MyInterface.class);
when(mock.foo()).thenReturn(...);
//..etc
Run Code Online (Sandbox Code Playgroud)