Added by Alex Ruiz, last edited by Alex Ruiz on Nov 02, 2009  (view change)

Labels:

Enter labels to add to this page:
Wait Image 
Looking for a label? Just start typing.

Extending FEST-Assert with Custom Conditions

Assertions classes provided by FEST-Assert can be extended by using custom conditions (instances of org.fest.assertions.Condition.)

For example, the following condition verifies that the characters in a String are in uppercase:

// package org.fest.assert.sample;

class UpperCaseCondition extends Condition<String> {
  public boolean matches(String value) {
    if(isEmpty(value)) return false;
    return value.equals(value.toUpperCase());
  }

  public static UpperCaseCondition isUpperCase() {
    return new UpperCaseCondition("Uppercase");
  }
}

This example shows how to use such condition:

// import static org.fest.assert.sample.UpperCaseCondition.isUpperCase;
assertThat("hello").as("Greeting").satisfies(isUppercase());

which will fail with the message:

[Greeting] actual value:<'hello'> should satisfy condition:<Uppercase>

New in 1.2: "is" and "isNot"

FEST-Assert also provides the methods is and isNot, which are aliases for satisfies and doesNotSatisfy respectively. These aliases work exactly the same as the original methods, with the difference that they can improve readability in certain cases.

In our previous example, we can change the name of the static factory method isUppercase to simply uppercase:

public static UpperCaseCondition upperCase() {
  return new UpperCaseCondition("Uppercase");
}

and use the alias is:

// import static org.fest.assert.sample.UpperCaseCondition.upperCase;
assertThat("hello").as("Greeting").is(uppercase());

which is shorter and easy to read than the original version!