Search code examples
javajunithamcrest

Matcher on multiple properties simultaneously on a Collection


Is possible to test multiple condition on each Matched item in a Collection?

I have a collection with given objects:

obj1: property1=A1, property2=B1

obj2: property1=A2, property2=B2

obj3: property1=A3, property2=B3

obj4: property1=A4, property2=B4

I want to check that property1 and property2 have simultaneously specified values.

Thank you for any advice.


Solution

  • Sure, that's possible. It would look something like this:

    Matcher<Item> matcher = new BaseMatcher<Item>() {
    
        @Override
        public boolean matches(Object item) {
            Item myItem = (Item) item;
            return check(myItem.property1, myItem.property2);
        }
    
        @Override
        public void describeTo(Description description) {
            // describe it
        }
    
    }
    

    The check function would have to test the combination of property1 and property2. This may be easiest using a HashMap, unless of course there's some way of calculating one from the other or something like that.