如何将Hamcrest匹配器应用于被测类的属性? [英] How to apply a Hamcrest matcher to the property of a class under test?

查看:119
本文介绍了如何将Hamcrest匹配器应用于被测类的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以构建组合的Hamcrest匹配器来测试对象和该对象的属性? -伪代码:

Is there a way to build a combined Hamcrest matcher which tests an object and the property of this object? - pseudo code:

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结束,其中包含这些抛出的异常的集合:

Background: I have a JUnit test, which iterates over a collection of dynamic objects. Each object is expected to throw an exception when processed. The exceptions are collected. The test is expected to end with a MultipleFailureException containing a collection of these thrown exceptions:

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

推荐答案

我认为您可能正在寻找 hasPropertyWithValue

I think you might be looking for hasProperty or hasPropertyWithValue

请参见此处的示例:我以前处理过的另一个示例;在这里,我们检查是否有Quote方法getModels()返回PhoneModel的集合,并且该集合中的一项具有等于LG_ID的属性makeId和等于NEXUS_4_ID的modelId.

Another example of something I worked with previously; here we check if we have a Quote method getModels() returns a collection of PhoneModel and one of the items in the collection has a property makeId that is equal to LG_ID and modelId that is equal to NEXUS_4_ID.

            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 约定.

For this to work, hamcrest relies on you adopting JavaBean conventions.

这篇关于如何将Hamcrest匹配器应用于被测类的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆