6

I wrote a custom matcher to compare my objects. It all works except for the describeMismatchSafely method. I kept simplyfing and simplyfing, until I got this:

public static TypeSafeMatcher<IMyObj > equalTo(final IMyObj expected) {

    return new TypeSafeMatcher<IMyObj >() {

        @Override
        public void describeTo(final Description description) {
            description.appendText("this value");
        }

        @Override
        public void describeMismatchSafely(final IMyObj myObj, final Description mismatchDescription) {
            mismatchDescription.appendText(" the wrong value");
        }

        @Override
        protected boolean matchesSafely(IMyObj actual) {
            return false;
        }
   }
}

The method describeTo works just fine, but describeMismatchSafely always prints myObj.toString() instead of the message I want it to:

java.lang.AssertionError: Expected: this value got:

I googled custom matchers implementations and it seemed everybody was overriding the describeMismatchSafely method and it was working just fine for them. Is there a reason mine should not work?

Mauzik
  • 78
  • 6
  • WFM. Can you show your assertion? – Joe Dec 23 '14 at 11:28
  • assertThat(expected, NodeEqualsMatcher.equalTo(actual)); – Mauzik Dec 23 '14 at 11:36
  • possible duplicate of [Is there a version of JUnit assertThat which uses the Hamcrest 'describeMismatch' functionality?](http://stackoverflow.com/questions/3915635/is-there-a-version-of-junit-assertthat-which-uses-the-hamcrest-describemismatch) – Joe Dec 23 '14 at 12:01
  • Which class's `assertThat` are you using? – Joe Dec 23 '14 at 12:56

1 Answers1

1

If you're using JUnit's org.junit.Assert#assertThat then upgrade to JUnit 4.11 to pick up a bug fix.

Joe
  • 29,416
  • 12
  • 68
  • 88
  • I am using hamcrest-all-1.3.jar downloaded from here (and it still doesn't work): https://code.google.com/p/hamcrest/downloads/detail?name=hamcrest-1.3.zip&can=2&q=label%3AFeatured) – Mauzik Dec 23 '14 at 12:41
  • 1
    Worked, thanks! I needed to have both the latest version of Hamcrest and JUnit in order for this to work. The problem is I am developing for Android and the Eclipse downloaded from here: http://developer.android.com/tools/help/adt.html had an older version of JUnit, so I needed to manually download the JUnit 4.12 and link it to my project instead of the Eclipse JUnit. – Mauzik Dec 23 '14 at 13:26