首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在JsonUnit中创建具有多个参数的匹配器

如何在JsonUnit中创建具有多个参数的匹配器
EN

Stack Overflow用户
提问于 2021-02-13 09:32:07
回答 1查看 369关注 0票数 1

我希望创建一个具有多个参数(例如isBetween)的自定义匹配器,并在JsonUnit中使用它进行比较。我该怎么做?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-13 09:32:07

它类似于一值匹配器

代码语言:javascript
复制
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());
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66183628

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档