【问题标题】:How to apply a Hamcrest matcher to the property of a class under test?如何将 Hamcrest 匹配器应用于被测类的属性?
【发布时间】:2015-10-14 10:48:49
【问题描述】:

有没有办法构建一个组合的 Hamcrest 匹配器来测试一个对象和这个对象的属性? - 伪代码:

both(
  instanceof(MultipleFailureException.class)
).and(
  // pseudo code starts
  adapt(
    new Adapter<MultipleFailureException, Iterable<Throwable>()
    {
      public Iterable<Throwable> getAdapter(MultipleFailureException item)
      {
        return item.getFailures();
      }
    }, 
    // pseudo code ends
    everyItem(instanceOf(IllegalArgumentException.class))
  )
)

背景:我有一个 JUnit 测试,它迭代动态对象的集合。每个对象在处理时都应抛出异常。收集异常。测试应该以包含这些抛出异常的集合的 MultipleFailureException 结束:

protected final ExpectedException expectation = ExpectedException.none();
protected final ErrorCollector collector = new ErrorCollector();

@Rule
public RuleChain exceptionRules = RuleChain.outerRule(expectation).around(collector);

@Test
public void testIllegalEnumConstant()
{
  expectation.expect(/* pseudo code from above */);
  for (Object object : ILLEGAL_OBJECTS)
  {
    try
    {
      object.processWithThrow();
    }
    catch (Throwable T)
    {
      collector.addError(T);
    }
  }
}

【问题讨论】:

    标签: java junit hamcrest junit-rule


    【解决方案1】:

    我想你可能正在寻找hasPropertyhasPropertyWithValue

    查看示例:https://theholyjava.wordpress.com/2011/10/15/hasproperty-the-hidden-gem-of-hamcrest-and-assertthat/

    我以前使用过的另一个例子;这里我们检查是否有Quote 方法getModels() 返回PhoneModel 的集合,并且集合中的一个项目具有等于LG_ID 的属性makeId 和等于NEXUS_4_ID 的modelId

                assertThat(quote.getModels(),
                                hasItem(Matchers.<PhoneModel> hasProperty("makeId",
                                                equalTo(LG_ID))));
                assertThat(quote.getModels(),
                                hasItem(Matchers.<PhoneModel> hasProperty("modelId",
                                                equalTo(NEXUS_4_ID))));
        }
    

    为此,hamcrest 依赖于您采用 JavaBean 约定。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多