Search code examples
javajunithamcrest

How write a compound Hamcrest statement (with a logical "or" operation)


How would I go about writing the following JUnit assert with Hamcrest?

assertTrue(var1 == 5 || var2 == 10);

I can't use the anyOf() matcher wrapper because I dont need multiple matchers, I need multiple statements, one for each variable var1 and var2


Solution

  • You could write this as a single Hamcrest assertion by turning your variables into a single composite object:

    assertThat(ImmutableList.of(var1, var2),
        either(contains(is(5), anything()))
        .or(contains(anything(), is(10))));
    

    I would suggest that this is not particularly easy to understand, nor does it help explain what this would mean and why this represents success.