如何将 Android SingleLaunchActivityTestCase 转换为 ActivityTestRule? (仪器单元测试)

How to convert Android SingleLaunchActivityTestCase to ActivityTestRule? (Instrumentation unit test)

SingleLaunchActivityTestCase says that this class is now deprecated, and it should be replaced with ActivityScenarioRule or ActivityTestRule 的文档。但是这是怎么做到的呢?

SingleLaunchActivityTestCase 允许 Activity 启动一次并保持打开状态;那么这段时间可以进行多次测试运行,然后Activity关闭。 ActivityTestRule 似乎没有此功能 - 它总是为每个 @Test 方法重新启动 Activity。

那么是否可以让 ActivityTestRule 启动一次 Activity 并保持打开状态,我如何确保 context(来自 activityTestRule.getActivity())不每个 @Test 函数为 null?

示例代码 here.

在您的设置中使用 constructor that does not start the activity by default (setting the launchActivity argument to false). Then use launchActivity(),但不是在每个测试方法中。这样你就可以自己启动一次,但是每次测试都会在同一个实例上运行。

您可能还希望在测试 class 结束时显式完成 activity 以进行清理。

注意:虽然这通常不是测试的最佳做法,因为测试可能相互依赖(这不是一个好主意),或者根据它们的顺序提供不正确的结果 运行等,因为在这种情况下,activity 状态从一个测试持续到下一个测试。

我用 Jon Adams 的回答举例说明:

@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,当测试 运行 作为 class 或单独进行时。