unit-testing - 如何测试定制的 hamcrest 匹配器?

标签 unit-testing junit matcher hamcrest

我正在编写一些自定义匹配器来简化 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/

相关文章:

java - 将值添加到 Junit 中的 multiPart(使用 Jersey )

objective-c - 为什么第一次运行 "XCTestCase -measureBlock:"需要这么长时间?

reactjs - 如何从 @react-native-firebase/auth 模拟身份验证

java - 无法进行交易调用

JAVA正则表达式失败

java - (模式和匹配器)未发现所有模式匹配

clang - 特定节点上的 AST 匹配器

javascript - 如何检查多个 chai-http 请求何时真正在 block 之前的 mocha 中完成?

从一组单元测试中组成一个组合测试套件程序

spring-boot - 使用 @ExtendWith(MockitoExtension.class) 的 Spring Boot JUnit 5 测试不工作 - 模拟为空,MockitoJUnitRunner 工作