有时我会在应用程序中遇到罕见的错误.但是我不能复制它,因为它非常罕见.所以,我决定写一个简单的Espresso 测试:

@RunWith(AndroidJUnit4::class)
@LargeTest
class MainActivityTest {

    val password = "1234"

    @Rule @JvmField
    var mActivityRule: ActivityTestRule<MainActivity> = ActivityTestRule(MainActivity::class.java)

    @Test
    fun checkNotesListNotEmpty() {
        onView(withId(R.id.password_edit_text)).perform(typeText(password))
        onView(withId(R.id.notes_recycler_view)).check { view, noMatchingViewException ->
            if (noMatchingViewException != null) throw noMatchingViewException
            assertThat((view as RecyclerView).adapter.itemCount,  Matchers.`is`(1))
        }
    }
}

如何在匹配失败时循环此测试并停止它?

推荐答案

使用@Repeat注释:

@RunWith(AndroidJUnit4.class)
public class MyTest {

    @Rule
    public RepeatRule repeatRule = new RepeatRule();

    @Test
    @Repeat(100)
    fun checkNotesListNotEmpty() {
    }

但你必须自己实施:

重复Java :

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 )
@Target({ METHOD, ANNOTATION_TYPE })
public @interface Repeat {
    int value() default 1;
}

RepeatRule.java:

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

        @Override
        public void evaluate() throws Throwable {
            for (int i = 0; i < repeat; i++) {
                statement.evaluate();
            }
        }

    }

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

Kotlin相关问答推荐

用普通Kotlin理解Gradle的Kotlin DSL'""

在Webflux应用程序中通过kotlin协程启动fire and forget job

Spring Boot 3:为Kotlin中的TestRestTemplate配置读取超时

Kotlin stlib中是否有用于将列表<;对<;A,B&>;转换为对<;列表<;A&>,列表<;B&>;的函数

为什么Kotlin有次构造函数和init块?

KMM:编译失败:意外的 IrType 类型:KIND_NOT_SET

Kotlin 有垃圾收集器吗?如果是这样,它基于哪种算法?

如何在 Kotlin for Android 上使用setTextColor(hexaValue),

Android数据绑定在自定义视图中注入ViewModel

对列表中数字的子集求和

Kotlin 1.2.21 + SimpleXml 2.3.0 - consume List error (must mark set get method)

Kotlin 中 lambda 表达式中的默认参数

Hilt Activity 必须附加到 @AndroidEntryPoint 应用程序

Kotlin内联扩展属性

Android:在 DAO 中使用 Room 数据库和 LiveData 架构

接口中的属性不能有支持字段

使用 kotlin 每 3 位数添加逗号或点

kotlin中密封类和密封接口的区别是什么

如何在伴随对象中使用泛型

可见性不适用于 Kotlin