【问题标题】:Can the output of the "but: was" clause be customised?“but: was”子句的输出可以自定义吗?
【发布时间】:2014-08-09 18:51:02
【问题描述】:

我正在尝试编写一个自定义匹配器,它可以在对象图的深处导航以检查重要属性。

assertThat( writeRequest, hasRole("admin") );

如果失败,我希望看到如下消息:

Expected: "admin"
     but: was "read-only"

但是,当断言失败时,它会在writeRequest 上打印出toString(),这意味着我想要的信息将在字符串的深处。更糟糕的是,沿着对象图生成了一个不@Override Object.toString() 的类,因此您甚至无法找出(没有日志记录或断点)用户的实际角色!

那么,在 Hamcrest 中,有没有办法自定义出现在 but: was 子句中的输出?

【问题讨论】:

    标签: hamcrest


    【解决方案1】:

    tl;dr: 覆盖 org.hamcrest.BaseMatcher.describeMismatch(Object item, Description description)


    在使用 org.hamcrest.collection.IsIterableWithSize 运行测试时,我发现测试失败并显示以下消息:

    Expected: an iterable with size <1>
         but: iterable size was <0>
    

    其中有一个自定义的but 子句!

    查看source code for IterableWithSize 我注意到字符串"iterable size" 正在作为参数featureName 传递给org.hamcrest.FeatureTypeMatcher。通过org.hamcrest.TypeSafeDiagnosingMatcher 跟踪这个,我发现了describeMismatch(Object,Description) 方法。由于BaseMatcher 具有该方法的实现,因此如果您让 IDE 生成缺少方法的存根,您将错过它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-02
      • 1970-01-01
      • 2016-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多