PowerMock(with mockito) simple unit test error
22,423
@PrepareForTest({MyService.class}) is a class level annotation.
You should add it at the same location as @RunWith(PowerMockRunner.class)
You can find more information at their github
Author by
user842225
Updated on July 09, 2022Comments
-
user842225 almost 2 years
I am using Mockito + PowerMock to write a simple unit test for the following singleton class:
public class MyService { private static MyService service; private List<School> schoolList; private MyService(){ // test case error complains here! School school = new School(); schoolList.add(school); } public static Singleton getInstance( ) { return service; } protected static void printSchool( ) { School school = schoolList.get(0); print(school); } }
My Test case:
@RunWith(PowerMockRunner.class) public class MyServiceTest { @PrepareForTest({MyService.class}) @Test public void testPrintSchool() { // enable mock static function PowerMockito.mockStatic(MyService.class); MyService mockService = PowerMockito.mock(MyService.class); PowerMockito.when(MyService.getInstance()) .thenReturn(mockService); } }
I run my test, but got the following error:
java.lang.RuntimeException: Invoking the beforeTestMethod method on PowerMock test listener org.powermock.api.extension.listener.AnnotationEnabler@3ab19451 failed. at com.xyz.MyService.<init>(MyService.java:12) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:526) at org.mockito.internal.util.reflection.FieldInitializer$ParameterizedConstructorInstantiator.instantiate(FieldInitializer.java:257) at org.mockito.internal.util.reflection.FieldInitializer.acquireFieldInstance(FieldInitializer.java:124) at org.mockito.internal.util.reflection.FieldInitializer.initialize(FieldInitializer.java:86) at org.mockito.internal.configuration.injection.ConstructorInjection.processInjection(ConstructorInjection.java:52) ...
As you can see, the error complains about
MyService.java:12
line 12, that is the lineSchool school = new School();
inMyService
constructor.Why I get this error, how to get rid of it?