hamcrest / JavaHamcrest

Java (and original) version of Hamcrest

Home Page:http://hamcrest.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Create assertThat with reason supplier to defer calculation of reason

Rhobal opened this issue · 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);
    }

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.