Class ExpectFailure

java.lang.Object
com.google.common.truth.ExpectFailure
All Implemented Interfaces:
TestRule

public final class ExpectFailure extends Object
A utility for testing that assertions against a custom Subject fail when they should, plus a utility to assert about parts of the resulting failure messages.

Usage:

  AssertionError e =
      expectFailure(whenTesting -> whenTesting.that(cancelButton).isVisible());
  assertThat(e).factKeys().containsExactly("expected to be visible");

...

private static AssertionError expectFailure(
    SimpleSubjectBuilderCallback<UiElementSubject, UiElement> assertionCallback) {
  return expectFailureAbout(uiElements(), assertionCallback);
}
ExpectFailure also supports a legacy approach, which we no longer recommend now that all Truth users can use lambdas. That approach is based on the JUnit @Rule system:
@Rule public final ExpectFailure expectFailure = new ExpectFailure();

...

    expectFailure.whenTesting().about(uiElements()).that(cancelButton).isVisible();
    assertThat(expectFailure.getFailure()).factKeys().containsExactly("expected to be visible");

ExpectFailure is similar to JUnit's assertThrows (JUnit 4, JUnit 5). We recommend it over assertThrows when you're testing a Truth subject because:

  • It performs additional checks:
  • It instructs Truth to generate failure messages without adding lines like "value of: foo()" for assertThat(foo()).... calls that it detects in the test bytecode. Truth doesn't provide guarantees for when such lines will be generated, so tests become more resilient without them.