【问题标题】:Assert that Collection contains 2 Objects with same property using matchers [duplicate]使用匹配器断言集合包含 2 个具有相同属性的对象 [重复]
【发布时间】:2014-07-25 04:28:22
【问题描述】:

我有以下场景,我想测试 someFunction():

Collection<MyObject> objects = someFunction(someInput);
assertThat(objects , contains(hasProperty("property", is(propertyIWantToTest))));

如果 Collection&lt;MyObject&gt; objects 根据传递给 someFunction()someInput 应该只有 1 个 MyObject object,这将正常工作。 但是,someInput 在某些情况下,Collection&lt;MyObject&gt; objects 应该有 2 个或更多 MyObject object 包含相同的 propertyIWantToTest 对象。 有没有办法使用 Hamcrest 匹配器来测试它?

以下是更接近我愿意实现的目标:

assertThat(objects , contains(exactlyTwoTimes(hasProperty("property", is(propertyIWantToTest)))));

【问题讨论】:

    标签: java testing junit junit4 hamcrest


    【解决方案1】:

    如果您想验证每个项目都具有该属性,并且恰好有两个项目,请使用everyItemhasSize

    assertThat(objects, everyItem(hasProperty("property", is(propertyIWantToTest))));
    assertThat(objects, hasSize(2));
    

    如果您想专门测试集合的内容,但碰巧两个预期项目相同,请使用变量和containsInAnyOrder

    Matcher<MyObject> m = hasProperty("property", is(propertyIWantToTest));
    assertThat(objects, containsInAnyOrder(m, m));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-23
      • 2016-01-05
      相关资源
      最近更新 更多