对我而言,以下步骤有效:
1.将androidx库替换为此处发布的库。我的决赛app/build.gradle
看起来像这样:
android {
...
defaultConfig {
...
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
...
}
dependencies {
...
testImplementation 'junit:junit:4.12'
// Core library
androidTestImplementation 'androidx.test:core:1.2.0'
// AndroidJUnitRunner and JUnit Rules
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test:rules:1.2.0'
// Assertions
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.ext:truth:1.2.0'
androidTestImplementation 'com.google.truth:truth:0.42'
// Espresso dependencies
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
然后,我将ExampleInstrumentTest.java
班级中导入的模块手动替换为最新班级:
import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.rule.ActivityTestRule;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4ClassRunner.class)
public class ExampleInstrumentedTest {
...
@Rule
public final ActivityTestRule<MainActivity> main = new ActivityTestRule<>(MainActivity.class, true);
@Before
public void init() {
...
}
@Test
public void listCount() {
...
}
@Test
public void useAppContext() {
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
Assert.assertEquals("in.curioustools.aad_x_testing2", appContext.getPackageName());
System.out.println("useAppContext : Test Ran");
}
}
让我烦恼的是,InstrumentationRegistery
该类仍被弃用。所以我InstrumentationRegistry.getInstrumentation().getTargetContext();
从androidx.test.platform.app.InstrumentationRegistry
课堂上使用。