7

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 */
}
Community
  • 1
  • 1
keiki
  • 3,260
  • 3
  • 30
  • 38

1 Answers1

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
dkatzel
  • 31,188
  • 3
  • 63
  • 67
  • How can I suppress calling the constructor of the enum? Is it similar to that call? My experience with mockito is limited. – keiki Mar 24 '14 at 10:02
  • If you go with the interface route, then the enum isn't used at all so the constructor isn't called. – dkatzel Mar 24 '14 at 14:03
  • So if somewhere in the code Enumclass.ENUM.isEnabled() is called is this possible to be suppresed? – keiki Mar 24 '14 at 14:13
  • I tried and didn't work for me as we.. @keiki were you able to figure out how to do it? – Shruts_me Apr 17 '17 at 00:50
  • @Shruts_me Not really. We are actually calling one of those setters now :( – keiki Apr 18 '17 at 12:28