Skip to content

Commit

Permalink
[hotfix][tests] Add matcher for finding exception cause by Class
Browse files Browse the repository at this point in the history
  • Loading branch information
zentol committed Feb 16, 2021
1 parent 0a17665 commit d227b38
Showing 1 changed file with 37 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,11 @@ public static <T> FutureWillFailMatcher<T> futureWillCompleteExceptionally(Durat
return futureWillCompleteExceptionally(Throwable.class, timeout);
}

/** Checks for a {@link Throwable} that matches by class. */
public static Matcher<Throwable> containsCause(Class<? extends Throwable> failureCause) {
return new ContainsCauseMatcher(failureCause);
}

/** Checks for a {@link Throwable} that matches by class and message. */
public static Matcher<Throwable> containsCause(Throwable failureCause) {
return new ContainsCauseAndMessageMatcher(failureCause);
Expand Down Expand Up @@ -229,6 +234,38 @@ public void describeTo(Description description) {
}
}

private static final class ContainsCauseMatcher extends TypeSafeDiagnosingMatcher<Throwable> {

private final Class<? extends Throwable> failureCause;

private ContainsCauseMatcher(Class<? extends Throwable> failureCause) {
this.failureCause = failureCause;
}

@Override
protected boolean matchesSafely(Throwable throwable, Description description) {
final Optional<Throwable> optionalCause =
findThrowable(throwable, cause -> cause.getClass() == failureCause);

if (!optionalCause.isPresent()) {
description
.appendText("The throwable ")
.appendValue(throwable)
.appendText(" does not contain the expected failure cause ")
.appendValue(failureCause.getSimpleName());
}

return optionalCause.isPresent();
}

@Override
public void describeTo(Description description) {
description
.appendText("Expected failure cause is ")
.appendValue(failureCause.getSimpleName());
}
}

private static final class ContainsCauseAndMessageMatcher
extends TypeSafeDiagnosingMatcher<Throwable> {

Expand Down

0 comments on commit d227b38

Please sign in to comment.