【源码】hamcrest 源码阅读 定制 Matcher

23 篇文章 2 订阅

前言

实现 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));
    }

  • 结果
    测试通过
    在这里插入图片描述

后记

拓展一个实现,能够独立使用,也能加入到已有的体系里面组合使用。这种设计很合理,希望以后复杂的业务场景能够把这种思想用起来。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值