前言
-
需求
- 按官方的规范拓展自己的 Matcher
- 将自己的 Matcher 加入到现有的谓词用法里 (allOf 、anyOf 等)
实现 LowestPriceMatcher
判断价格是否为最低价。lowestPrice 是变化的,每次都需要实例化一个 LowestPriceMatcher
public class LowestPriceMatcher extends TypeSafeMatcher<BigDecimal> {
private final BigDecimal lowestPrice;
public LowestPriceMatcher(BigDecimal lowestPrice) {
this.lowestPrice = lowestPrice;
}
@Override
public void describeTo(Description description) {
description.appendText("使用最低价格购入, 花费").appendValue(lowestPrice).appendText("元");
}
@Override
protected boolean matchesSafely(BigDecimal item) {
return lowestPrice.equals(item);
}
@Override
protected void describeMismatchSafely(BigDecimal item, Description mismatchDescription) {
mismatchDescription.appendText("当前产品的价格: ").appendValue(item).appendText("元")
.appendText(" 不是最低价格。最低价格为:").appendValue(lowestPrice);
}
}
- 使用
@Test
public void test() {
LowestPriceMatcher matcher = new LowestPriceMatcher(BigDecimal.ZERO);
// 使用 MatcherAssert.assertThat;
assertThat(BigDecimal.TEN, matcher);
}
- 效果
结合 allOf
allOf 包含的 Matcher必须全部满足。以下代码执行结果与上文相同。
@Test
public void test() {
LowestPriceMatcher equalLowerPrice = new LowestPriceMatcher(BigDecimal.ZERO);
BigDecimalCloseTo oneCentOverLowestPrice = new BigDecimalCloseTo(BigDecimal.ZERO, new BigDecimal("0.01"));
// 使用 org.hamcrest.core.AllOf.allOf;
assertThat(new BigDecimal("0.01"), allOf(equalLowerPrice, oneCentOverLowestPrice));
}
结合 anyOf
anyOf 包含的 Matcher,只要满足一个条件即可。
@Test
public void test() {
LowestPriceMatcher equalLowerPrice = new LowestPriceMatcher(BigDecimal.ZERO);
BigDecimalCloseTo oneCentOverLowestPrice = new BigDecimalCloseTo(BigDecimal.ZERO, new BigDecimal("0.01"));
// 使用 org.hamcrest.core.AllOf.anyOf;
assertThat(new BigDecimal("0.01"), anyOf(equalLowerPrice, oneCentOverLowestPrice));
}
- 结果
测试通过
后记
拓展一个实现,能够独立使用,也能加入到已有的体系里面组合使用。这种设计很合理,希望以后复杂的业务场景能够把这种思想用起来。