【问题标题】:PowerMock(with mockito) simple unit test errorPowerMock(with mockito) 简单的单元测试错误
【发布时间】:2015-12-01 14:50:59
【问题描述】:

我正在使用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 行,即MyService 构造函数中的School school = new School(); 行。

为什么会出现这个错误,如何消除它?

【问题讨论】:

    标签: unit-testing mockito powermock powermockito


    【解决方案1】:

    @PrepareForTest({MyService.class}) 是一个类级别的注解。

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

    相同的位置

    您可以在他们的github找到更多信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-07
      • 1970-01-01
      • 2011-08-27
      • 1970-01-01
      • 2020-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多