diff --git a/src/main/java/org/junit/experimental/results/ResultMatchers.java b/src/main/java/org/junit/experimental/results/ResultMatchers.java index 98778a9f924e..c593a135661d 100644 --- a/src/main/java/org/junit/experimental/results/ResultMatchers.java +++ b/src/main/java/org/junit/experimental/results/ResultMatchers.java @@ -66,9 +66,9 @@ public void describeTo(Description description) { * contains {@code string} */ public static Matcher hasFailureContaining(final String string) { - return new BaseMatcher() { - public boolean matches(Object item) { - return item.toString().contains(string); + return new TypeSafeMatcher() { + public boolean matchesSafely(PrintableResult item) { + return item.failureCount() > 0 && item.toString().contains(string); } public void describeTo(Description description) { diff --git a/src/test/java/org/junit/tests/experimental/results/ResultMatchersTest.java b/src/test/java/org/junit/tests/experimental/results/ResultMatchersTest.java index 024fe32b09fa..4c121b965c93 100644 --- a/src/test/java/org/junit/tests/experimental/results/ResultMatchersTest.java +++ b/src/test/java/org/junit/tests/experimental/results/ResultMatchersTest.java @@ -1,14 +1,21 @@ package org.junit.tests.experimental.results; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - import org.junit.Test; +import org.junit.experimental.results.PrintableResult; import org.junit.experimental.results.ResultMatchers; import org.junit.experimental.theories.Theory; +import org.junit.runner.Description; +import org.junit.runner.notification.Failure; + +import java.util.ArrayList; +import java.util.Collections; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; public class ResultMatchersTest { + @Test public void hasFailuresHasGoodDescription() { assertThat(ResultMatchers.failureCountIs(3).toString(), @@ -20,4 +27,20 @@ public void hasFailuresDescriptionReflectsInput(int i) { assertThat(ResultMatchers.failureCountIs(i).toString(), containsString("" + i)); } + + @Test + public void hasFailureContaining_givenResultWithNoFailures() { + PrintableResult resultWithNoFailures = new PrintableResult(new ArrayList()); + + assertThat(ResultMatchers.hasFailureContaining("").matches(resultWithNoFailures), is(false)); + } + + @Test + public void hasFailureContaining_givenResultWithOneFailure() { + PrintableResult resultWithOneFailure = new PrintableResult(Collections.singletonList( + new Failure(Description.EMPTY, new RuntimeException("my failure")))); + + assertThat(ResultMatchers.hasFailureContaining("my failure").matches(resultWithOneFailure), is(true)); + assertThat(ResultMatchers.hasFailureContaining("his failure").matches(resultWithOneFailure), is(false)); + } }