问题
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