This example will show how to use hamcrest bean matchers to validate object properties values. Hamcrest in conjunction with junit testing is a powerful way to validate java objects. In the example set up we have created a Truck class that will be used in each of the snippets.
Setup
Object has property
In this snippet we will use hamcrest hasProperty matcher to validate that the Truck object has a property named model.
Object has property with value
Similar to above, we will use the hamcrest hasProperty matcher to validate that the Truck object has model. In addition we will pass a valueMatcher to examine the property's value, in this case we will check if the model's value is equal to 'Big 10'.
Object has same property as
The samePropertyValuesAs matcher will check all of the values of one object to another java bean properties. If all of the values of pickupTruck1 equal pickupTruck2 the junit test case will pass.