我正在寫一些自定義匹配器來簡化junit聲明。他們大多數擴展TypeSafeMatcher,所以我只需要覆蓋三種方法:如何測試自定義hamcrest匹配器?
public class NoneConstraintViolationMatcher<T> extends
TypeSafeMatcher<Set<ConstraintViolation<T>>> {
@Override
public void describeTo(Description description) {
description.appendText("None constraint violations found");
}
@Override
protected void describeMismatchSafely(Set<ConstraintViolation<T>> item,
Description mismatchDescription) {
mismatchDescription.
appendText("Unexpected constraint violation found, but got ");
mismatchDescription.appendValueList("", ",", "", item);
}
@Override
protected boolean matchesSafely(Set<ConstraintViolation<T>> item) {
return item.isEmpty();
}
}
我的問題是如何測試它們?我目前的解決方案是
public class NoneConstraintViolationMatcherUnitTests {
private NoneConstraintViolationMatcher<Object> matcher =
new NoneConstraintViolationMatcher<Object>();
@Test
public void returnsMatchedGivenNoneConstraintViolations() throws Excetpion {
assertTrue(matcher.matches(.....));
}
@Test
public void returnsMismatchedGivenSomeConstraintViolations() throws Excetpion {
assertThat(matcher.matches(.....), is(false));
}
@Test
public void returnsConstraintViolationsFoundWhenMismatched()
throws Exception {
StringBuilder out = new StringBuilder();
//I don't find anything could be used to assert in description
StringDescription description = new StringDescription(out);
matcher.describeMismatch(..someCvx, description);
assertThat(out.toString(),
equalTo("Unexpected constraint violation found, but got "));
}
}
是在我腦海中的另一個解決方案是寫一個JUnit測試,並使用@rule的ExpectedException(與handleAssertionError設置爲true)。
你們如何測試匹配者?提前致謝。
謝謝你的迴應。使用此解決方案測試描述是否容易? – Hippoom