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

时间:2022-10-31 18:59:58

I have this array of values that are considered wrong

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

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

In my test I am clicking on the edit text, inserting the text and pressing back to close the keyboard.

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

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

and then check if the error view is showing

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

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

This is working but I would like output somewhere in the test log the value which it failed for because when the test does fail I do not know which value was being tested Is this possible?

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

Thanks

谢谢

1 个解决方案

#1


5  

You can implement the FailureHandler interface to define custom failure handling for Espresso:

您可以实现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);          
    }
}

Before your tests are running, create and set the custom error handler like this:

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

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

#1


5  

You can implement the FailureHandler interface to define custom failure handling for Espresso:

您可以实现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);          
    }
}

Before your tests are running, create and set the custom error handler like this:

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

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