2017-04-09 55 views
1

我想測試我的Android應用程序的靜態方法。Android,PowerMock:文件夾中的測試類androidTest:javassist.NotFoundException:

我的build.gradle:

dependencies { 
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2' 
    androidTestCompile "org.mockito:mockito-android:2.7.21" 
    androidTestCompile "org.powermock:powermock-api-mockito:1.6.6" 
    androidTestCompile 'org.powermock:powermock-module-junit4:1.6.6' 

    testCompile 'junit:junit:4.12' 
    testCompile 'org.powermock:powermock-api-mockito:1.6.6' 
    testCompile 'org.powermock:powermock-module-junit4:1.6.6' 
} 

我對Android應用PowerMock測試:

import static org.hamcrest.MatcherAssert.assertThat; 
import static org.mockito.Mockito.when; 
import static org.powermock.api.mockito.PowerMockito.mockStatic; 

@RunWith(PowerMockRunner.class) 
@PrepareForTest(StringUtil.class) 
public class StringUtilInstrumentedTest { 
    private Context context; 

    @Before 
    public void init() { 
     context = InstrumentationRegistry.getTargetContext(); 
    } 

    @Test 
    public void decliningAge() { 
     mockStatic(StringUtil.class); 

     // use Mockito to set up your expectation 
     String expected = "first"; 
     when(StringUtil.calcAge(context, 1)).thenReturn(expected); 
     assertThat(StringUtil.calcAge(context, 1), is(expected));  
    } 
} 

但是,當我嘗試啓動測試,拋出異常:

I/TestRunner(32154): java.lang.ClassNotFoundException: com.mycompany.StringUtilInstrumentedTest 
I/TestRunner(32154): at java.lang.Class.classForName(Native Method) 
android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1879) 
I/TestRunner(32154): Caused by: java.lang.IllegalStateException: Failed to transform class with name com.mycompany.StringUtilInstrumentedTest. Reason: com.mycompany.StringUtilInstrumentedTest 
org.powermock.core.classloader.MockClassLoader.loadMockClass(MockClassLoader.java 
I/TestRunner(32154): Caused by: javassist.NotFoundException: com.mycompany.StringUtilInstrumentedTest 
I/TestRunner(32154): at javassist.ClassPool.get(ClassPool.java:452) 

爲什麼我得到這個錯誤?

回答

0

如果StringUtilInstrumentedTest駐留在src/test/java那麼可以使用PowerMock。但如果它在src/androidTest/java那麼它不會工作。

PowerMock不支持Android Instrumentation測試。請參考:https://github.com/powermock/powermock/issues/594

對不起,遲到的迴應。 PowerMock無法在Android上運行,因爲PowerMock正在使用JVM字節碼操作。如果你在JVM上運行它,它將工作。

+0

是的,我從文件夾「src/androidTest/java」開始StringUtilInstrumentedTest。 – Alexei

相關問題