Skip to content

Commit

Permalink
Migrate off failWithRawMessageAndCause, which is being deprecated.
Browse files Browse the repository at this point in the history
I'm sorry that the replacement is so ugly. Our reason for not supporting this directly is partially that it's needed by only ~1% of subjects. But mostly, we've over time taken the position that Truth is intended for only the "assert" phases of the "arrange, act, assert" testing process. Exceptions, on the other hand, usually come from the earlier phases.

Unfortunately, I still owe everyone a long explanation of *why* we have come to this position. If it's bugging you now, let me know, and I can make it happen.

(And yes, in this particular case, we're basically arguing that Your Subject Is Wrong. Sorry: I'm not trying to get you to delete it or recant or anything; I'm just trying to explain where we're coming from.)

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=192278109
  • Loading branch information
cpovirk authored and ronshapiro committed Apr 11, 2018
1 parent fa918f7 commit 48b3f62
Showing 1 changed file with 31 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,7 @@ public Subject<?, Object> providedValue() {
try {
got = provider.get();
} catch (Exception e) {
failWithRawMessageAndCause(
String.format("checked provider <%s> threw an exception", provider), e);
failWithCauseAndMessage(e, "checked provider <%s> threw an exception", provider);
return ignoreCheck().that(new Object());
}
return check().withMessage("value provided by <%s>", provider).that(got);
Expand All @@ -80,4 +79,34 @@ public ThrowableSubject thrownException() {
failWithBadResults("threw", "an exception", "provided", got);
return ignoreCheck().that(new Throwable());
}

/*
* Hack to get Truth to include a given exception as the cause of the failure. It works by letting
* us delegate to a new Subject whose value under test is the exception. Because that makes the
* assertion "about" the exception, Truth includes it as a cause.
*/

private void failWithCauseAndMessage(Throwable cause, String format, Object... args) {
check().about(unexpectedFailures()).that(cause).doFail(format, args);
}

private static Factory<UnexpectedFailureSubject, Throwable> unexpectedFailures() {
return new Factory<UnexpectedFailureSubject, Throwable>() {
@Override
public UnexpectedFailureSubject createSubject(FailureMetadata metadata, Throwable actual) {
return new UnexpectedFailureSubject(metadata, actual);
}
};
}

private static final class UnexpectedFailureSubject
extends Subject<UnexpectedFailureSubject, Throwable> {
UnexpectedFailureSubject(FailureMetadata metadata, @Nullable Throwable actual) {
super(metadata, actual);
}

void doFail(String format, Object... args) {
failWithRawMessage(format, args);
}
}
}

0 comments on commit 48b3f62

Please sign in to comment.