Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

hasProperty, the Hidden Gem of Hamcrest (and assertThat)

DZone's Guide to

hasProperty, the Hidden Gem of Hamcrest (and assertThat)

· Java Zone
Free Resource

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

If you got used to JUnit 4′s assertThat with various matchers (of course you will need junit-dep.jar and hamcrest.jar to get the full set instead of the small subset integrated in junit.jar), make sure you don’t overlook the matcher hasProperty. It is very useful if you have non-trivial objects and cannot use some more flexible language like Groovy for your unit tests.

The advantage of hasProperty is that it allows you to check a particular property (or more properties with allOf) of an object while ignoring the others – pretty useful if the object has 20 properties and checking just one is enough for you. (Admittedly, an object with 20 properties is an abomination but hey, that’s the real legacy word!)

Example – check that collection contains two Images with some file names:

assertThat("Expected images", (Iterable<Object>) hotel.getImages()
  , containsInAnyOrder(hasProperty("filename", is("radisson1.jpg"))
     , hasProperty("filename", is("radisson2.jpg"))));

The failure message in this case isn’t as clear as I might wish but still this is the best solution I can think of.

From http://theholyjava.wordpress.com/2011/10/15/hasproperty-the-hidden-gem-of-hamcrest-and-assertthat/

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}