JavaHamcrest icon indicating copy to clipboard operation
JavaHamcrest copied to clipboard

Create assertThat with reason supplier to defer calculation of reason

Open Rhobal opened this issue 5 years ago • 1 comments

The reason is only required when an assertion fails. If a Supplier could be provided instead of a String, an expensive or destructive construction of a reason (such as reading an InputStream) could be deferred. Example code:

    public static <T> void assertThat(Supplier<String> reason, T actual, Matcher<? super T> matcher) {
        if (!matcher.matches(actual)) {
            Description description = new StringDescription();
            description.appendText(reason.get())
                       .appendText(System.lineSeparator())
                       .appendText("Expected: ")
                       .appendDescriptionOf(matcher)
                       .appendText(System.lineSeparator())
                       .appendText("     but: ");
            matcher.describeMismatch(actual, description);
            
            throw new AssertionError(description.toString());
        }
    }

    public static <T> void assertThat(String reason, T actual, Matcher<? super T> matcher) {
    	assertThat(() -> reason, actual, matcher);
    }

Rhobal avatar Apr 30 '20 20:04 Rhobal

This seems like a reasonable improvement, though issues #206 and #207 will have to be resolved first, as Supplier is a 1.8 functional interface.

tumbarumba avatar May 01 '20 13:05 tumbarumba