Skip to content

Hamcrest matcher to match multiple attributes of an object within a single assertion.

Notifications You must be signed in to change notification settings

sandromancuso/bean-property-matcher

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 
 
 
 
 
 
 

Repository files navigation

BeanMatcher

Hamcrest matcher to match multiple attributes of an object within a single assertion.

How to use it

    // Static imports
    
    import static org.craftedsw.beanpropertymatcher.matcher.BeanMatcher.has;
    import static org.craftedsw.beanpropertymatcher.matcher.BeanPropertyMatcher.property;
    import static org.hamcrest.MatcherAssert.assertThat;
    import static org.hamcrest.Matchers.equalTo;
    import static org.hamcrest.Matchers.greaterThan;

    // Imagine that you have a method that returns an object Person

    Person person = new Person();
    person.setFirstName("Sandro");
    person.setAge(25);
    person.setLastName("Mancuso");
    
    // Then you can test it like that
    
    assertThat(person, has(
                            property("firstName", equalTo("Another dude")),  // Mistmatch
                            property("age", greaterThan(18)),  // Use any matcher 
                            property("lastName", equalTo("Mancuso"))));

If you run this test, you will get a message like

    java.lang.AssertionError: 
        Expected: property "firstName" = "Another dude" 
        but: property "firstName" was "Sandro" 

Now, change the age check to:

   property("age", greaterThan(60)) 

Now you should get:

    java.lang.AssertionError: 
    Expected: property "firstName" = "Another dude" , property "age" = a value greater than <60> 
    but: property "firstName" was "Sandro" , property "age" <25> was less than <60>

Testing object graphs

You can also do this

    Person person = new Person();
    person.setFirstName("Sandro");
    person.setAge(35);
		
    Country uk = new Country();
    uk.setName("United Kingdom");
		
    Address address = new Address();
    address.setPostcode("1234556");
    address.setCity("London");
    address.setCountry(uk);
		
    person.setAddress(address);
		
    assertThat(person, has(
                            property("firstName", equalTo("Sandro")),
                            property("age", greaterThan(18)),
                            property("address.city", equalTo("London")),
                            property("address.postcode", equalTo("1234556")),
                            property("address.country.name", equalTo("United Kingdom"))));		

Enjoy!!!

About

Hamcrest matcher to match multiple attributes of an object within a single assertion.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages