Search code examples
javajunitjunit4hamcrest

JUnit Hamcrest assertion


Is there a Hamcrest Matcher that cleanly lets me assert that the result of a method, that returns a Collection of objects, has at least one object that contains a property with certain value?

For example:

class Person {
   private String name;
}

The method under test returns a collection of Person. I need to assert that at least one Person is called Peter.


Solution

  • First, you need to create a Matcher that can match a Person's name. Then, you could use hamcrest's CoreMatchers#hasItem to check if a Collection has an item this mathcer matches.

    Personally, I like to declare such matchers anonymously in static methods as a sort of syntactic sugaring:

    public class PersonTest {
    
        /** Syntactic sugaring for having a hasName matcher method */
        public static Matcher<Person> hasName(final String name) {
            return new BaseMatcher<Person>() {
                public boolean matches(Object o) {
                   return  ((Person) o).getName().equals(name);
                }
    
                public void describeTo(Description description) {
                    description.appendText("Person should have the name ")
                               .appendValue(name);
                }
            };
        }
    
        @Test
        public void testPeople() {
            List<Person> people = 
                Arrays.asList(new Person("Steve"), new Person("Peter"));
    
            assertThat(people, hasItem(hasName("Peter")));
        }
    }