Created
November 20, 2013 08:29
-
-
Save watanabeshuji/7559704 to your computer and use it in GitHub Desktop.
ItemMatcher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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