【问题标题】:How to use Hamcrest's AssertThat for String[]如何将 Hamcrest 的 AssertThat 用于 String[]
【发布时间】:2015-07-15 20:19:56
【问题描述】:

所以我一直在环顾四周并试图找到解决此问题的方法,但我遇到了编译器错误或奇怪的期望,或两者兼而有之。 所以我们开始:

this.mockPersonNode.setProperty("fname",new String[] {"John"});
...unrelated code...
//validate traits
final String[] fname = (String[]) groovy.getProperty("firstName");
//This is where my problems lie
assertThat(fname, hasProperty("John"));

所以这段代码编译得很好,但是当我在 Maven 中构建它时,测试失败了,因为:Expected: hasProperty("John"), got:[John]

所以我做了一些查看并检查了人们在这里回答的其他问题,但我得到了编译错误,我显然做错了 assertThat 但应该如何设置 assertThat?

【问题讨论】:

    标签: java maven hamcrest assertthat


    【解决方案1】:

    使用hasItemInArray 匹配器:

    assertThat(fname, hasItemInArray("John"));
    

    hasProperty 匹配器匹配 Java Bean 属性。

    【讨论】:

      【解决方案2】:

      如果您想断言数组 fname 包含项目 John 而没有其他内容,您可以使用 IsArrayContainingInOrder 匹配器 (Matchers.arrayContaining):

      assertThat(fname, arrayContaining("John"));
      

      如果您只关心fname 中的至少一项是John,请按照@hzpz 的建议使用IsArrayContaining 匹配器(Matchers.hasItemInArray)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-03
        • 1970-01-01
        • 1970-01-01
        • 2014-11-21
        • 2017-09-02
        • 2013-11-17
        • 2017-02-18
        • 2011-04-24
        相关资源
        最近更新 更多