1

我想创建一个具有多个参数的自定义匹配器(例如 isBetween)并将其用于 JsonUnit 中的比较。我怎么做?

4

1 回答 1

1

它类似于具有一个值的匹配器

Matcher<?> betweenMatcher = new BetweenMatcher();
assertThatJson("{\"test\": 3.14}")
    .withMatcher("isBetween", betweenMatcher)
    .isEqualTo("{\"test\":\"${json-unit.matches:isBetween}3.1,3.2\"}");
 ...

private static class BetweenMatcher extends BaseMatcher<Object> implements ParametrizedMatcher {
    private BigDecimal lowerBound;
    private BigDecimal upperBound;

    public boolean matches(Object item) {
        if (!(item instanceof BigDecimal)) {
            return false;
        }
        BigDecimal actualValue = (BigDecimal) item;
        return actualValue.compareTo(lowerBound) >= 0 && actualValue.compareTo(upperBound) <= 0;
    }

    public void describeTo(Description description) {
        description.appendValue(lowerBound).appendText(" and ").appendValue(upperBound);
    }

    @Override
    public void describeMismatch(Object item, Description description) {
        description.appendText("is not between ").appendValue(lowerBound).appendText(" and ").appendValue(upperBound);
    }

    public void setParameter(String parameter) {
        String[] tokens = parameter.split(",");
        this.lowerBound = new BigDecimal(tokens[0].trim());
        this.upperBound = new BigDecimal(tokens[1].trim());
    }
}
于 2021-02-13T09:32:07.603 回答