Ersen Osman
Ersen Osman

Reputation: 7247

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

Upvotes: 5

Views: 3845

Answers (3)

agoff
agoff

Reputation: 7164

Kotlin translation of thaussma's response

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)
    }
}

Upvotes: 0

Kamran Ahmed
Kamran Ahmed

Reputation: 7761

You can even log your custom messages for particular assertions by catching their Exception and throwing your own instead like:

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

Upvotes: 0

thaussma
thaussma

Reputation: 9886

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));

Upvotes: 13

Related Questions