2015-12-01 152 views
0

我使用Mockito + PowerMock写以下单例类简单的单元测试:PowerMock(带的Mockito)简单的单元测试误差

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 [email protected] 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();行。

为什么我得到这个错误,如何摆脱它?

回答

3

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

您应该在相同的位置@RunWith添加它(PowerMockRunner.class)

您可以在自己的github

找到更多的信息