Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ItemMatcher
public class ItemMatcher extends TypeSafeMatcher<Item> {
public static Matcher<Item> item(Item item) {
return new ItemMatcher(item);
}
private Item expected;
private String fieldName;
private Object expectedValue;
private Object actualValue;
public ItemMatcher(Item expected) {
this.expected = expected;
}
@Override
protected boolean matchesSafely(Item actual) {
if (actual == null && expected == null) {
return true;
} else if (actual == null || expected == null) {
return false;
}
if (notEquals(actual.id, expected.id)) {
fieldName = "id";
actualValue = actual.id;
expectedValue = expected.id;
return false;
}
if (notEquals(actual.name, expected.name)) {
fieldName = "name";
actualValue = actual.name;
expectedValue = expected.name;
return false;
}
if (notEquals(actual.price, expected.price)) {
fieldName = "price";
actualValue = actual.price;
expectedValue = expected.price;
return false;
}
if (notEquals(actual.description, expected.description)) {
fieldName = "description";
actualValue = actual.description;
expectedValue = expected.description;
return false;
}
return true;
}
private boolean notEquals(Object o1, Object o2) {
if (o1 == null) {
return o2 != null;
} else {
return !o1.equals(o2);
}
}
@Override
public void describeTo(Description desc) {
if (fieldName == null || expected == null) {
desc.appendValue(expected);
} else {
desc.appendValue(expected);
desc.appendText(String.format("%n - %s is ", fieldName)).appendValue(expectedValue).appendText(", but ")
.appendValue(actualValue);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment