Hamcrest bean matchers

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

class Truck {

    private String model;
    private String make;
    private int year;

    public Truck(String model, String make, int year) {
        super();
        this.model = model;
        this.make = make;
        this.year = year;
    }

    // getters/setters
}

Object has property

In this snippet we will use hamcrest hasProperty matcher to validate that the Truck object has a property named model.

@Test
public void object_has_property () {

    Truck pickupTruck = new Truck("Ram", "Dodge", 1965);

    assertThat(pickupTruck, hasProperty("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'.

@Test
public void object_has_property_with_value () {

    Truck pickupTruck = new Truck("Big 10", "Chevy", 1976);

    assertThat(pickupTruck, hasProperty("model", equalTo("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.

@Test
public void object_has_property_values_as () {

    Truck pickupTruck1 = new Truck("Big 10", "Chevy", 1976);
    Truck pickupTruck2 = new Truck("Big 10", "Chevy", 1976);

    assertThat(pickupTruck1, samePropertyValuesAs(pickupTruck2));
}