Android Espresso:如何在测试失败时添加自己的日志输出?

Android Espresso: How do I add my own log output when a test fails?

我有这个被认为是错误的值数组

 public static final String[] WRONG_VALUES = {"1000","4000","2000"};

在我的测试中,我单击编辑文本,插入文本并按回键关闭键盘。

  onView(withId(R.id.inputField)).perform(click(), replaceText(text), pressBack());

然后检查错误视图是否显示

onView(withId(R.id.error)).matches(not(isCompletelyDisplayed()));

这是有效的,但我想在测试日志的某处输出它失败的值,因为当测试失败时我不知道正在测试哪个值 这可能吗?

谢谢

您可以实现 FailureHandler 接口来定义 Espresso 的自定义故障处理:

public class CustomFailureHandler implements FailureHandler {

    private final FailureHandler delegate;

    public CustomFailureHandler(@NonNull Instrumentation instrumentation) {
        delegate = new DefaultFailureHandler(instrumentation.getTargetContext());
    }

    @Override
    public void handle(final Throwable error, final Matcher<View> viewMatcher) {            
        // Log anything you want here

        // Then delegate the error handling to the default handler which will throw an exception
        delegate.handle(error, viewMatcher);          
    }
}

在您的测试 运行 之前,像这样创建和设置自定义错误处理程序:

Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
Espresso.setFailureHandler(new CustomFailureHandler(instrumentation));

您甚至可以通过捕获它们的 Exception 并抛出您自己的消息来记录特定断言的自定义消息,例如:

try {
    onView().check() // Some test here
} catch (Exception ex) {
    throw new Exception("This test failed with this custom message logged: " + ex.getMessage());
}

的 Kotlin 翻译
class CustomFailureHandler(instrumentation: Instrumentation) : FailureHandler {
    var delegate: DefaultFailureHandler = DefaultFailureHandler(instrumentation.targetContext)

    override fun handle(error: Throwable?, viewMatcher: Matcher<View>?) {
        // Log anything you want here

        // Then delegate the error handling to the default handler which will throw an exception
        delegate.handle(error, viewMatcher)
    }
}