I know that this is usually bad practice, but in my case it is necessary.
I have a case where Enum contains a class to get some information. So Enum creates an instance of these calss in its constructor.
public enum MyEnum { CONSTANT(new MyImpl()); private final MyImpl myImpl; private MyEnum(final MyImpl impl) { this.myImpl = impl; } public void sayHello() { System.out.println(this.myImpl.getSomethingToSay()); } }
MyImpl.java is just a class with a single method that returns a string.
public class MyImpl { public String getSomethingToSay() { return "Hello!"; } }
Now, finally, unit test:
import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.testng.PowerMockTestCase; @RunWith(MockitoJUnitRunner.class) @PrepareForTest({ MyImpl.class, MyEnum.class }) public class MyEnumTest extends PowerMockTestCase { @Test public void testSmth2() throws Exception { MyImpl impl = Mockito.mock(MyImpl.class); Mockito.when(impl.getSomethingToSay()).thenReturn("It works!"); PowerMockito.whenNew(MyImpl.class).withAnyArguments().thenReturn(impl); System.out.println(impl.getSomethingToSay()); System.out.println(new MyImpl().getSomethingToSay()); MyEnum.CONSTANT.sayHello(); } }
Output:
It works! Hello! Hello!
But it should be 3 times bigger!
java enumeration unit-testing mockito mocking
Zarathustra
source share