如何在具有多个参数的 JsonUnit 中创建匹配器
How to create a matcher in JsonUnit with more than one parameter
我想创建一个包含多个参数(例如 isBetween)的自定义匹配器,并将其用于 JsonUnit 中的比较。我该怎么做?
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());
}
}
我想创建一个包含多个参数(例如 isBetween)的自定义匹配器,并将其用于 JsonUnit 中的比较。我该怎么做?
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());
}
}