Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 412
Ersen Osman Avatar asked Jul 20 '16 13:07

Ersen Osman


1 Answers

You can implement the FailureHandler interface to define custom failure handling for 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));
like image 155
thaussma Avatar answered Oct 21 '22 14:10

thaussma