我想在Android应用中测试2个静态方法。所以我使用PowerMock。
我写了2个测试。一个单元测试和一个仪器化单元测试。
我的android build.gradle:
dependencies {
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'
}
这里代码:
@RunWith(PowerMockRunner.class)
@PrepareForTest(StringUtil.class)
public class StringUtilTest {
@Test
public void isCorrectEmailStub() {
// mock all the static methods in a class called "StringUtil"
mockStatic(StringUtil.class);
String INCORRECT_EMAIL_TO_CHECK = "incorrect_email_some.com";
when(StringUtil.isCorrectEmail(INCORRECT_EMAIL_TO_CHECK)).thenReturn(true);
assertThat(StringUtil.isCorrectEmail(INCORRECT_EMAIL_TO_CHECK), is(true));
}
}
它工作正常。行。
这里代码:
@RunWith(PowerMockRunner.class)
@PrepareForTest(StringUtil.class)
public class StringUtilInstrumentedTest {
private static String TAG;
private Context context;
@Before
public void init() {
TAG = StringUtilInstrumentedTest.class.getName();
context = InstrumentationRegistry.getTargetContext();
}
@Test
public void decliningAge() {
// mock all the static methods in a class called "StringUtil"
mockStatic(StringUtil.class);
// use Mockito to set up your expectation
String expected = "first";
when(StringUtil.decliningAge(context, 1)).thenReturn(expected);
assertThat(StringUtil.decliningAge(context, 1), is(expected));
}
}
但是当我运行此测试时,我收到错误:
java.lang.ClassNotFoundException: com.mycompany.StringUtilInstrumentedTest
at java.lang.Class.classForName(Native Method)
at java.lang.Class.forName(Class.java:324)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1879)
Caused by: java.lang.IllegalStateException: Failed to transform class with name com.mycompany.StringUtilInstrumentedTest.Reason: com.mycompany.StringUtilInstrumentedTest
at org.powermock.core.classloader.MockClassLoader.loadMockClass(MockClassLoader.java:284)
at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:192)
at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass1(DeferSupportingClassLoader.java:77)
at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:67)
at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
Caused by: javassist.NotFoundException: com.mycompany.StringUtilInstrumentedTest
at javassist.ClassPool.get(ClassPool.java:452)
at org.powermock.core.classloader.MockClassLoader.loadMockClass(MockClassLoader.java:262)