Android Studio - 单元测试模拟应用重启

Android Studio - Unit Tests Simulate App Restart

您好,我想使用单元测试来查看我的数据保存结构是否正常工作问题是,我不知道如何以编程方式模拟重启。

这是一个示例单元测试。

(AppData 只是一个 Class 来保存各种事物,例如包含多个条目的购物清单。)

@Test
    public void getDataAfterRestart(){
        //Save a Entry
        AppData appData = new AppData();
        appData.addShoppingEntry(new ShoppingEntry("Bread"));
        appData.save();


        //************************
        //Restart the Application*
        //************************


        //After the App reopend it self check if the Entry is still here
        int entries = appData.getShoppingEntries().size();

        assertEquals(1,entries);
}

有哪些好的做法可以解决此类问题?

提前致谢!

重新启动您的应用意味着您需要与底层 Android 操作系统进行交互以测试正确的行为。这意味着您需要编写插桩测试而不是单元测试。在 Android 中,我们使用 Testing Library in AndroidX. In this case, you probably need to use UI Automator 中提供的工具编写 Instrumented 测试,以便直接与设备交互以停止您的应用程序,然后重新启动它。