Retry TestRule for Android Espresso tests

This tutorial shows how to add Retry Test Rule to your Espresso UI automation tests. If a test fails it will retry test ‘X’ times. The code snippets are for Java and Kotlin projects.

1. First, we create the Retry TestRule

/**
* Retry test rule used to retry test that failed.
*
Retry failed test 3 times
*/
class RetryTestRule(val retryCount: Int = 3) : TestRule {

private val TAG = RetryTestRule::class.java.simpleName

override fun apply(base: Statement, description: Description): Statement {
return statement(base, description)
}

private fun statement(base: Statement, description: Description): Statement {
return object : Statement() {
@Throws(Throwable::class)
override fun evaluate() {
var caughtThrowable: Throwable? = null

// implement retry logic here
for (i in 0 until retryCount) {
try {
base.evaluate()
return
} catch (t: Throwable) {
caughtThrowable = t
Log.e(TAG, description.displayName + ": run " + (i + 1) + " failed")
}
}

Log.e(TAG, description.displayName + ": giving up after " + retryCount + " failures")
throw caughtThrowable!!
}
}
}
}

Java:

public class RetryTest {
public static class Retry implements TestRule {
private int retryCount;

public Retry(int retryCount) {
this.retryCount = retryCount;
}

public Statement apply(Statement base, Description description) {
return statement(base, description);
}

private Statement statement(final Statement base, final Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
Throwable caughtThrowable = null;

// implement retry logic here
for (int i = 0; i < retryCount; i++) {
try {
base.evaluate();
return;
} catch (Throwable t) {
caughtThrowable = t;
Log.e(TAG, description.getDisplayName() + ": run " + (i + 1) + " failed");
}
}
Log.e(TAG, description.getDisplayName() + ": giving up after " + retryCount + " failures");
throw caughtThrowable;
}
};
}
}
}

2. Then we add TestRule to test class:

@Rule
@JvmField
val mRetryTestRule = RetryTestKotlin.Retry(3)

Java:

@Rule
public RetryTest.Retry mRetryTestRule = new RetryTest.Retry(3);

3. Run Espresso tests.

Thanks for reading! ping me if you have a question about Retry TestRule.

software engineer, read, swim, travel. apps: https://goo.gl/rDuuQw https://goo.gl/15GvfE

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store