How to implement a hamcrest match

I want to run this line of code:

assertThat(contextPin.get(), equalTo(pinPage.getPinObjFromUi()));

but I want the magazine to be informative

means that I could know which fields are not equal.

So, I thought about implementing a match.

I have googled, but I could not write it correctly

since my method could not combine the actual and expected objects.

here is my code:

how can i write it clean?

 public class PinMatcher extends TypeSafeMatcher<Pin> { private Pin actual; private Object item; public PinMatcher(Pin actual) { this.actual = actual; } @Override protected boolean matchesSafely(Pin item) { return false; } @Override public void describeTo(Description description) { } //cannot override this way @Override public boolean matches(Object item){ assertThat(actual.title, equalTo(expected.title)); return true; } //cannot access actual when called like this: // assertThat(contextPin.get(), new PinMatcher.pinMatches(pinPage.getPinObjFromUi())); @Override public boolean pinMatches(Object item){ assertThat(actual.title, equalTo(expected.title)); return true; } } 
+7
java equals hamcrest matcher
source share
2 answers

Try something else like this:

 package com.mycompany.core; import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher; public class PinMatcher extends TypeSafeMatcher<Pin> { private Pin actual; public PinMatcher(Pin actual) { this.actual = actual; } @Override protected boolean matchesSafely(Pin item) { return actual.title.equals(item.title); } @Override public void describeTo(Description description) { description.appendText("should match title ").appendText(actual.title); } } 
+4
source share

Your matches should get expected in the constructor and compare it with the parameter "actual value" item passed to matchesSafely . You should not override matches .

This will be consistent with what assertThat expects:

 assertThat(actual, matcher-using-expected); 

I think string comparisons are type safe and will serve as a good example.

+1
source share

All Articles