How to apply a Hamcrest matcher to the property of a class under test?

随声附和 提交于 2019-12-12 18:33:05

问题


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

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

回答1:


I think you might be looking for hasProperty or hasPropertyWithValue

See here for an example: https://theholyjava.wordpress.com/2011/10/15/hasproperty-the-hidden-gem-of-hamcrest-and-assertthat/

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

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



来源:https://stackoverflow.com/questions/33123344/how-to-apply-a-hamcrest-matcher-to-the-property-of-a-class-under-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!