我有这个被认为是错误的值数组
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()));
这是有效的,但是我想在测试日志中的某处输出它失败的值,因为当测试失败时我不知道正在测试哪个值 这可能吗?
由于
答案 0 :(得分: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);
}
}
在测试运行之前,创建并设置自定义错误处理程序,如下所示:
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
Espresso.setFailureHandler(new CustomFailureHandler(instrumentation));
答案 1 :(得分:0)
您甚至可以通过捕获Exception
并抛出自己的自定义消息来记录特定断言的自定义消息,例如:
try {
onView().check() // Some test here
} catch (Exception ex) {
throw new Exception("This test failed with this custom message logged: " + ex.getMessage());
}
答案 2 :(得分:0)
thaussma's response 的 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)
}
}