Я использовал ответ Джона Адамса, чтобы уточнить пример:
@RunWith(AndroidJUnit4.class)
@LargeTest
public class KeepActivityOpenDuringTests {
@Rule
public ActivityTestRule<MyActivity> activityTestRule =
new ActivityTestRule<>(MyActivity.class, true, false);
/**
* When running the class as a test suite, setUp() is called repeatedly
* for each test method. Use setupDone to prevent multiple setups.
*/
private static boolean setupDone;
// Static to persist across multiple tests
private static Context context;
private static MyActivity activityUnderTest;
@Before
public void setUp() throws Exception {
// Launch the Activity manually, once, to get a real Context object.
if (!setupDone) {
activityUnderTest = activityTestRule.launchActivity(null);
context = (Context) activityUnderTest;
// continue setup of singletons...
setupDone = true;
}
}
@Test
public void test1() {
// Use context ...
}
@Test
public void test2() {
// Use activityUnderTest ...
}
@AfterClass
public static void cleanUp() throws Exception {
if (activityUnderTest != null) {
activityUnderTest.finish();
// Prevent any potential memory leaks
activityUnderTest = null;
context = null;
setupDone = false;
}
}
}
Он работает как SingleLaunchActivityTestCase, когда тесты запускаются как класс или по отдельности.