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();
行。
爲什麼我得到這個錯誤,如何擺脫它?