'Shazamcrest' is a library that extends the functionality of hamcrest.
Assertions on complete beans are made simpler by serialising the actual and expected beans to json, and comparing the two. The diagnostics are leveraging the comparison functionality of IDEs like Eclipse or IntelliJ.
Having a Person bean with the following structure:
Person person |-- String name |-- String surname |-- Address address |-- String streetName |-- int streetNumber
to compare two Person beans with Shazamcrest we would write:
assertThat(actualPerson, sameBeanAs(expectedPerson));
instead of explicitly match every field of the bean and sub-beans:
assertThat(actualPerson, allOf(
hasProperty("name", equalTo(expectedPerson.name)),
hasProperty("surname", equalTo(expectedPerson.surname)),
hasProperty("address", allOf(
hasProperty("streetName", equalTo(expectedPerson.address.streetName)),
hasProperty("streetNumber", equalTo(expectedPerson.address.streetNumber)))
)
));
If the person address streetName does not match the expectations, the following diagnostic message is displayed:
org.junit.ComparisonFailure: address.streetName Expected: Via Roma got: Via Veneto expected:<... "streetName": "Via [Roma]", "streetNumber...> but was:<... "streetName": "Via [Veneto]", "streetNumber...>
The exception thrown is a ComparisonFailure which can be used by IDEs like Eclipse and IntelliJ to display a visual representation of the differences.
Note: in order to get the ComparisonFailure on mismatch the "assertThat" to use is com.shazam.shazamcrest.MatcherAssert.assertThat rather than org.hamcrest.MatcherAssert.assertThat
If we are not interested in matching the street name, we can ignore it:
assertThat(actualPerson, sameBeanAs(expectedPerson).ignoring("address.streetName"));
If we want to make sure that the street name starts with "Via" at least:
assertThat(actualPerson, sameBeanAs(expectedPerson).with("address.streetName"), startsWith("Via"));
where startsWith is an Hamcrest matcher.
To use, download the zip or add the following to your project's pom.xml:
<dependency>
<groupId>com.shazam</groupId>
<artifactId>shazamcrest</artifactId>
<version>0.7</version>
</dependency>
- If a bean contains data with circular references, a StackOverflowError will be thrown during comparison.
- Sets and Maps with same data are serialised in non deterministic order, generating random comparison failures.