Search code examples
androidunit-testingandroid-lifecycleandroid-instrumentation

Can I get the instrumentation test to kill and restart the app process?


I need to test a use case where the application starts from a clean state - i.e. the process has not been running before the test starts. From what I see from logcat, all instrumentation tests run under one single process instance/session, so the outcome of the test in my case depends on whether or not it runs as #1 or not. It should not be this way - as we all know, unit tests (or instrumentation tests) should be autonomous.

Is there any way with the standard Android instrumentation test tools and functions I can force the TestRunner to restart the process before a given test? If not, are there hacks or third-party libraries that can help me achieve that? Or is there any way I can specifically say that test X must be run first (worst option but still)?

In specific, my test relates to the launching of activities through intents, and the intent flags (e.g. FLAG_ACTIVITY_CLEAR_TOP) in addition to the Activity launch mode (e.g. singleTop) and the state of the process, very much dictates the outcome of the test.


Solution

  • Assuming you are running with Espresso, there is not a clean way to pull this off. This is because Espresso runs in the same process as the application and thus killing the app will kill Espresso.

    The question is, do you need all the logic you want to execute in your Application or could it be ported to your Activity.onCreate()? With Espresso restarting an Activity is doable. If there is a need to restart the application because of global/singletons, removing these may be necessary. If this cannot be done you can look at other test automation frameworks like Appium which has some support for this.