Using conditions - alexruiz/fest-assert-2.x GitHub Wiki

(to main page)

Assertions classes provided by FEST-Assert can be extended by using custom conditions. (instances of org.fest.assertions.core.Condition).
You only have to implement org.fest.assertions.core.Condition which has a unique method : matches.

Then you can use it with methods : is(myCondition) or has(myCondition), both methods verify that the condition is met - just choose the one that makes your code the most readable.

The examples below comes from fest-examples and more specifically UsingConditionExamples.java.

Let's define jedi and jediPower conditions (actually the same but with different name to show is/has condition usage) :

private final Condition<String> jedi = new Condition<String>("jedi") {
  private final Set<String> jedis = set("Luke", "Yoda", "Obiwan");
  @Override
  public boolean matches(String value) {
    return jedis.contains(value);
  }
};

private final Condition<String> jediPower = new Condition<String>("jedi power") {
  // same implementation as jedi condition ... 
};

is(Condition) usage

assertThat("Yoda").is(jedi);
assertThat("Vader").isNot(jedi);
try {
  // condition not verified to show the clean error message 
  assertThat("Vader").is(jedi);
} catch (AssertionError e) {
  assertThat(e).hasMessage("expecting:<'Vader'> to be:<jedi>");
}

has(Condition) usage

assertThat("Yoda").has(jediPower);
assertThat("Solo").doesNotHave(jediPower);
try {
  // condition not verified to show the clean error message 
  assertThat("Vader").has(jediPower);
} catch (AssertionError e) {
  assertThat(e).hasMessage("expecting:<'Vader'> to have:<jedi power>");
}

####Verifying condition on collection elements

// import static org.fest.util.Collections.set;
assertThat(set("Luke", "Yoda")).are(jedi);
assertThat(set("Leia", "Solo")).areNot(jedi);

assertThat(set("Luke", "Yoda")).have(jediPower);
assertThat(set("Leia", "Solo")).doNotHave(jediPower);

assertThat(set("Luke", "Yoda", "Leia")).areAtLeast(2, jedi);
assertThat(set("Luke", "Yoda", "Leia")).haveAtLeast(2, jediPower);

assertThat(set("Luke", "Yoda", "Leia")).areAtMost(2, jedi);
assertThat(set("Luke", "Yoda", "Leia")).haveAtMost(2, jediPower);

assertThat(set("Luke", "Yoda", "Leia")).areExactly(2, jedi);
assertThat(set("Luke", "Yoda", "Leia")).haveExactly(2, jediPower);

####Combining conditions

assertThat("Vader").is(anyOf(jedi, sith));
assertThat("Solo").is(allOf(not(jedi), not(sith)));

where sith condition is defined as :

private final Condition<String> sith = new Condition<String>("sith") {
  private final Set<String> siths = set("Sidious", "Vader", "Plagueis");
  @Override
  public boolean matches(String value) {
    return siths.contains(value);
  }
};
⚠️ **GitHub.com Fallback** ⚠️