Mock an enum using Mockito in Java

15,487

There are two answers to that:

a) you could turn to some PowerMock-like mocking framework. My two cent(entences) there: don't do that. PowerMock opens a door to the land of pain; which you do not want to enter.

b) put interfaces on your enums

Seriously; I nowadays think that there is only one good use case for enums; and that is to use them as singletons that provide a certain service. And then, I do this:

public interface FooService { void foo(); }
class FooServiceImpl implements FooService { @Override void foo() ...
enum FooServiceProvider implements FooService {
   INSTANCE;
   private final FooService impl  = new FooServiceImpl();
   @Override foo() { impl.foo()

Of course, this doesn't really help when you use enums like you do. But the thing is: you shouldn't be using enums that way anyway. Because using enums this way leads to shattered code - every place that takes an enum variable is in need for such switch statements; with all the negative consequences when you add / remove enum cases.

So, in your case: consider turning to true OO designs - where you have abstract base classes that define methods; and then you use factories to create subclasses (probably based on enum switches) that give you objects that simply do the right thing.

Share:
15,487

Related videos on Youtube

Arthur Eirich
Author by

Arthur Eirich

Software developer at T-Systems on site services GmbH, Nuremberg. Married, have a daughter. Love developing in Java.

Updated on September 14, 2022

Comments

  • Arthur Eirich
    Arthur Eirich over 1 year

    How can I mock an enum for testing purposes using Mockito? Given this sample for the enum:

    public enum TestEnum {
     YES,
     NO
    }
    

    and this one for the method using the enum:

    public static boolean WorkTheEnum(TestEnum theEnum) {
    switch (theEnum) {
      case YES:
         return true;
      case NO:
         return false;
      default:
         // throws an exception here
     }
    }
    

    how can I mock the enum to reach the default branch of the switch loop? This answer says Mockito can't mock enums but the answer has also been provided more than a year ago. Do I can mock an enum meanwhile or have I to let the branch stay untested? Other Mocking frameworks can't be used.

    • J.Mengelle
      J.Mengelle almost 8 years
      Enum are like static class therefore you can't moke them with mokito.In your sample, the default is unreachable, so you can't test it.