Search code examples
javaandroidunit-testingandroid-studiorestart

Android Studio - Unit Tests Simulate App Restart


Hello I would like to use Unit Tests to see if my Data Save Structe is working the problem is, that I have no Idea how to Simulate a Restart programmatically.

Here is a Example Unit Test.

(AppData is just a Class to save various Things like a Shopping List with multiple Entries.)

@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);
}

What are some good practices, to deal with problems like this?

Thank you in advance!


Solution

  • Restarting your app implies that you need to interact with the underlying Android operating system in order to test the correct behavior. This means you need to write an Instrumented Test rather than a Unit Test. In Android, we write Instrumented tests using the tools provided in the Testing Library in AndroidX. In this case, you probably need to use UI Automator in order to interact with the device directly to stop your app and then restart it.