Search code examples
javaunit-testingjunitjunit4hamcrest

testing the order of a collection


Given a list of objects I'd like to test that they return in the correct order, but I would like to not assert the entire object.

For example I'd like to verify that they're in order by

id 1, 
id 2,
id 3,

or in another case

date mostRecent
date older
date oldest

or in yet another case

enum ValueA
enum ValueB
enum ValueC

basically I want to test that the sort I specified went through correctly but only a single property on the object actually affects this, so I'd like to specify my test with some variant of hasFirstItem( withPropertyEqualTo ... has secondItem( withPropertyEqualTo

I know I can write

 assertEquals( property, list.get(0).id )
 assertEquals( property, list.get(1).id )

but I'd rather do something that makes the failure a bit more obvious as to being a sort issue, and perhaps declaratively, testing the whole collection at once. Is this possible?


Solution

  • You should be able to use hamcrest's matcher hasProperty like this:

    public class Foo {
    
        private String a;
    
        public Foo(String a) {
            this.a = a;
        }
    
        public Object getStr() {
            return a;
        }
    
    
        public static void main(String[] args) {
            List<Foo> l = Arrays.asList(new Foo("a"), new Foo("b"));
            Assert.assertThat(l, contains(hasProperty("str", equalTo("a")),
                                          hasProperty("str", equalTo("b"))));
        }
    
    }
    

    where "str" is the name of the property you want to check. Note that this only works for methods named getXxx as it is aimed to test JavaBeans.