What is the recommended way to get this done programmatically?
The only possible option is to run ADB command adb shell pm clear package
before the test. The biggest problem is that it's kind of headache combining tests execution and shell commands.
However, we (at Mediafe) came with some solution that can work for you on regular unrooted device. All you need to do is to add an annotation. All the rest is done by running simple bash script.
Just add @ClearData
annotation before ANY of your tests and tada 🎉, ADB clear command will be executed before the test execution.
This is an example of such test:
@Test
@ClearData
public void someTest() {
// your test
}
The idea is as follows
- Read all tests by using
adb shell am instrument -e log true
- Build execution plan by parsing the output from (1)
- Run the execution plan line by line
Using the same idea these are all options you can easily support:
- Clear data
- Clear notification bar
- Parameterize
- Filter and run by tags
Use only annotations. Like this:
@Test
@ClearData
@Tags(tags = {"sanity", "medium"})
@Parameterized.Repeat(count = 3)
public void myTest() throws Exception {
String param = params[index];
// ...
}
Bonus! 🎁 For each failed test:
- Collect Logcat + stacktrace
- Record video (mp4)
- Dump DB (sqlite)
- Dump default shared preferences (xml)
- Collect dumpsys files like: battery, netstats and other.
In general, it's easy to add more options, since the tests are executed one by one from bash script rather than from gradle task.
📗 The full blog post: https://medium.com/medisafe-tech-blog/running-android-ui-tests-53e85e5c8da8
📘 The source code with examples: https://github.com/medisafe/run-android-tests
Hope this answers 6 years question ;)