PowerMock(带有mockito)简单的单元测试错误

时间:2015-12-01 14:51:00

标签: unit-testing mockito powermock powermockito

我正在使用Mockito + PowerMock为以下单例类编写一个简单的单元测试:

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);
   }
}

我的测试案例:

@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);
  }

}

我运行测试,但出现以下错误:

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)
...

正如您所看到的,该错误引发了MyService.java:12第12行,即School school = new School();构造函数中的行MyService

为什么我会收到此错误,如何摆脱它?

1 个答案:

答案 0 :(得分:3)

@PrepareForTest({MyService.class})是类级注释。

您应该将其添加到与 @RunWith(PowerMockRunner.class)

相同的位置

您可以在github

找到更多信息