我正在编写一些自定义匹配器来简化 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)。
你们如何测试匹配器?提前致谢。
最佳答案
我正在使用assertThat 来测试匹配功能。
@Test
public void returnsMatchedGivenNoneConstraintViolations() throws Excetpion {
assertThat(someObject, matcher);
}
@Test
public void returnsMismatchedGivenSomeConstraintViolations() throws Excetpion {
assertThat(someObject, not(matcher));
}
关于unit-testing - 如何测试定制的 hamcrest 匹配器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18349522/