diff --git a/core/src/main/java/com/google/common/truth/StringSubject.java b/core/src/main/java/com/google/common/truth/StringSubject.java index 8e71cc113..bfd55f10d 100644 --- a/core/src/main/java/com/google/common/truth/StringSubject.java +++ b/core/src/main/java/com/google/common/truth/StringSubject.java @@ -129,6 +129,11 @@ public void matches(@Nullable String regex) { fact("expected to match", regex), fact("but was", actual), simpleFact("Looks like you want to use .isEqualTo() for an exact equality assertion.")); + } else if (Platform.containsMatch(actual, regex)) { + failWithoutActual( + fact("expected to match", regex), + fact("but was", actual), + simpleFact("Did you mean to call containsMatch() instead of match()?")); } else { failWithActual("expected to match", regex); } @@ -149,6 +154,11 @@ public void matches(@Nullable Pattern regex) { simpleFact( "If you want an exact equality assertion you can escape your regex with" + " Pattern.quote().")); + } else if (regex.matcher(actual).find()) { + failWithoutActual( + fact("expected to match", regex), + fact("but was", actual), + simpleFact("Did you mean to call containsMatch() instead of match()?")); } else { failWithActual("expected to match", regex); } diff --git a/core/src/test/java/com/google/common/truth/StringSubjectTest.java b/core/src/test/java/com/google/common/truth/StringSubjectTest.java index 4e2f294d0..feb85d60d 100644 --- a/core/src/test/java/com/google/common/truth/StringSubjectTest.java +++ b/core/src/test/java/com/google/common/truth/StringSubjectTest.java @@ -216,6 +216,16 @@ public void stringMatchesStringLiteralFail() { .contains("Looks like you want to use .isEqualTo() for an exact equality assertion."); } + @Test + public void stringMatchesStringLiteralFailButContainsMatchSuccess() { + expectFailureWhenTestingThat("aba").matches("[b]"); + assertFailureValue("expected to match", "[b]"); + assertFailureValue("but was", "aba"); + assertThat(expectFailure.getFailure()) + .factKeys() + .contains("Did you mean to call containsMatch() instead of match()?"); + } + @Test @GwtIncompatible("Pattern") public void stringMatchesPattern() { @@ -249,6 +259,17 @@ public void stringMatchesPatternLiteralFail() { + " Pattern.quote()."); } + @Test + @GwtIncompatible("Pattern") + public void stringMatchesPatternLiteralFailButContainsMatchSuccess() { + expectFailureWhenTestingThat("aba").matches(Pattern.compile("[b]")); + assertFailureValue("expected to match", "[b]"); + assertFailureValue("but was", "aba"); + assertThat(expectFailure.getFailure()) + .factKeys() + .contains("Did you mean to call containsMatch() instead of match()?"); + } + @Test public void stringDoesNotMatchString() { assertThat("abcaqadev").doesNotMatch(".*aaa.*");