JUnit tests: Suppress enum constructor by mocking?

℡╲_俬逩灬. 提交于 2021-02-18 22:50:33

问题


I know that it is possible to mock a single enum(using How to mock an enum singleton class using Mockito/Powermock?), but I have like 1000 of enum values and they can call 5 different constructors. The enum values are often changing in development.

I want to really mock only one or two for my JUnit test. I don't care about the rest, but they are still instantiated, which calls some nasty stuff, which loads the values for the enum from the file system.

Yes I know It's very bad design. But for now I don't get the time to change it.

At the moment we have Mockito/powermock in use. But any framework, which can solve this sh** I mean bad design is welcome.

Let's say I have an enum similar to this:

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 */
}

回答1:


I agree with Nick-Holt who suggested adding an 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

}

Now you can use the normal mock abilities of Mockito without having to rely on Powermock

MyInterface mock = Mockito.mock(MyInterface.class);
when(mock.foo()).thenReturn(...);
//..etc


来源:https://stackoverflow.com/questions/22346396/junit-tests-suppress-enum-constructor-by-mocking

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!