Alexandr Alexandr - 1 month ago 28x
Android Question

Run espresso test multiple times

Sometimes I faced with rare bug in my application. But I can't reproduce it as it's very rare. So, I decided to write simple espresso test:

class MainActivityTest {

val password = "1234"

@Rule @JvmField
var mActivityRule: ActivityTestRule<MainActivity> = ActivityTestRule(

fun checkNotesListNotEmpty() {
onView(withId( { view, noMatchingViewException ->
if (noMatchingViewException != null) throw noMatchingViewException
assertThat((view as RecyclerView).adapter.itemCount, Matchers.`is`(1))

How can I loop this test and stop it when matching fails?


Use @Repeat annotation:

fun checkNotesListNotEmpty() {

But you have to implement it yourself:

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.METHOD;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention( RetentionPolicy.RUNTIME )
public @interface Repeat {
    int value() default 1;

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

public class RepeatRule implements TestRule {

    private static class RepeatStatement extends Statement {
        private final Statement statement;
        private final int repeat;    

        public RepeatStatement(Statement statement, int repeat) {
            this.statement = statement;
            this.repeat = repeat;

        public void evaluate() throws Throwable {
            for (int i = 0; i < repeat; i++) {


    public Statement apply(Statement statement, Description description) {
        Statement result = statement;
        Repeat repeat = description.getAnnotation(Repeat.class);
        if (repeat != null) {
            int times = repeat.value();
            result = new RepeatStatement(statement, times);
        return result;