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

Ers*_*man 5 android android-testing android-espresso

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

 public static final String[] WRONG_VALUES = {"1000","4000","2000"};
Run Code Online (Sandbox Code Playgroud)

在我的测试中,我点击编辑文本,插入文本,然后按回来关闭键盘.

  onView(withId(R.id.inputField)).perform(click(), replaceText(text), pressBack());
Run Code Online (Sandbox Code Playgroud)

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

onView(withId(R.id.error)).matches(not(isCompletelyDisplayed()));
Run Code Online (Sandbox Code Playgroud)

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

谢谢

tha*_*sma 9

您可以实现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);          
    }
}
Run Code Online (Sandbox Code Playgroud)

在测试运行之前,创建并设置自定义错误处理程序,如下所示:

Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
Espresso.setFailureHandler(new CustomFailureHandler(instrumentation));
Run Code Online (Sandbox Code Playgroud)