我正在编写一些自定义匹配器来简化 junit 断言。它们中的大多数都扩展了 TypeSafeMatcher,所以我只需要重写三个方法:
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)。
你们如何测试匹配器?提前致谢。