JUnit tests: Suppress enum constructor by mocking?
Asked Answered
I

1

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 */
}
Ilowell answered 12/3, 2014 at 8:55 Comment(3)
A setter in an enum? Uh, sh** is the right word indeedOrthogenetic
One quick fix might be to have the enum implement an interface that can then be mocked. It's a hack but would allow you to write your test now, then you should refactorUnfasten
Have a look at JMockit.Perutz
U
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
Unquestionable answered 18/3, 2014 at 21:0 Comment(5)
How can I suppress calling the constructor of the enum? Is it similar to that call? My experience with mockito is limited.Ilowell
If you go with the interface route, then the enum isn't used at all so the constructor isn't called.Unquestionable
So if somewhere in the code Enumclass.ENUM.isEnabled() is called is this possible to be suppresed?Ilowell
I tried and didn't work for me as we.. @Ilowell were you able to figure out how to do it?Heliograph
@Heliograph Not really. We are actually calling one of those setters now :(Ilowell

© 2022 - 2024 — McMap. All rights reserved.