The usage of assertThat can be described as:
assertThat(thePerson, equalTo(myPerson));Here, the subject of the assertion is the object thePerson that is the first method parameter. The second method parameter is a matcher for Person objects, here a matcher "equalTo" that checks one object is equal to another using the Object equals method, i.e. thePerson is equal to myPerson. Here let's assume, thePerson and myPerson are of Person type, and it overrides Object's equal method. Like "equalTo" there are other matchers defined by Hamcrest, they can be found at Hamcrest Matchers The main aim of Hamcrest is to make the Tests as readable as poosible.One such attepmt is "is" matcher.
assertThat(thePerson, is(equalTo(myPerson)));is matcher is a wrapper that doesn't add any extra behavior to the underlying matcher. The following assertions are all equivalent:
assertThat(thePerson, is(equalTo(myPerson))); assertThat(thePerson, equalTo(myPerson)); assertThat(thePerson, is(myPerson));The main power of Hamcrest lies in defining the Custom Matchers. Often we need to define more than one Custom Matchers and to use them in our Unit Tests, we need to statically import the indivudually. But there lies a consolidated approach for the same. An XML configuration file listing all the Matcher classes that should be searched for factory methods annotated with the org.hamcrest.Factory annotation.
<matchers> <!-- Custom extension 1 --> <factory class="com.action.hamcrest.AddressMatcher"/> <!-- Custom extension 2 --> <factory class="com.action.hamcrest.PersonMatcher"/> </matchers>The org.hamcrest.generator.config.XmlConfigurator command-line tool that comes with Hamcrest needs to be executed, which takes the XML configuration file and generates a single Java class that includes all the factory methods specified by the XML file. Running it with no arguments will display a usage message. Now let's traverse through the Custom Matchers. Here we have created 3 bean classes, they are: Address.class
public class Address {
private String houseNo;
private String street;
private String locality;
private String city;
private String state;
private int zipcode;
public String getHouseNo() {
return houseNo;
}
/**
* Other getter/setters, toString(), hashCode() and equals() method
*
*/
Person.class
public class Person {
private String name;
private Address address;
private Long ssn;
public String getName() {
return name;
}
/**
* Other getter/setters, toString(), hashCode() and equals() method
*
*/
Company.class
public class Company {
private String name;
private Address address;
private Set employee;
public String getName() {
return name;
}
/**
* Other getter/setters, toString(), hashCode() and equals() method
*
*/
No comments:
Post a Comment