Copy all instances of a class

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!

+8
java enumeration unit-testing mockito mocking
source share
1 answer

I found the faulty part.

I changed

 @RunWith(MockitoJUnitRunner.class) 

to

 @RunWith(PowerMockRunner.class) 

Now mocking work. But I must say that as John Skeet typed, there is no listing everywhere that he mocked the copy-copy. Therefore, in another call to Unit test MyEnum.CONSTANT.sayHello(); it will be printed again instead of Hello! .

+7
source share

All Articles