001    package org.junit.experimental.results;
002    
003    import org.hamcrest.BaseMatcher;
004    import org.hamcrest.Description;
005    import org.hamcrest.Matcher;
006    import org.hamcrest.TypeSafeMatcher;
007    
008    /**
009     * Matchers on a PrintableResult, to enable JUnit self-tests.
010     * For example:
011     *
012     * <pre>
013     * assertThat(testResult(HasExpectedException.class), isSuccessful());
014     * </pre>
015     */
016    public class ResultMatchers {
017        /**
018         * Matches if the tests are all successful
019         */
020        public static Matcher<PrintableResult> isSuccessful() {
021            return failureCountIs(0);
022        }
023    
024        /**
025         * Matches if there are {@code count} failures
026         */
027        public static Matcher<PrintableResult> failureCountIs(final int count) {
028            return new TypeSafeMatcher<PrintableResult>() {
029                public void describeTo(Description description) {
030                    description.appendText("has " + count + " failures");
031                }
032    
033                @Override
034                public boolean matchesSafely(PrintableResult item) {
035                    return item.failureCount() == count;
036                }
037            };
038        }
039    
040        /**
041         * Matches if the result has exactly one failure, and it contains {@code string}
042         */
043        public static Matcher<Object> hasSingleFailureContaining(final String string) {
044            return new BaseMatcher<Object>() {
045                public boolean matches(Object item) {
046                    return item.toString().contains(string) && failureCountIs(1).matches(item);
047                }
048    
049                public void describeTo(Description description) {
050                    description.appendText("has single failure containing " + string);
051                }
052            };
053        }
054    
055        /**
056         * Matches if the result has one or more failures, and at least one of them
057         * contains {@code string}
058         */
059        public static Matcher<PrintableResult> hasFailureContaining(final String string) {
060            return new BaseMatcher<PrintableResult>() {
061                public boolean matches(Object item) {
062                    return item.toString().contains(string);
063                }
064    
065                public void describeTo(Description description) {
066                    description.appendText("has failure containing " + string);
067                }
068            };
069        }
070    }