Extending FEST-Assert

FEST-Assert can be easily extended using:

  • Custom conditions
  • Custom assertion classes

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:

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:

assertThat("hello").as("Greeting").satisfies(isUppercase());

which will fail with the message "[Greeting] actual value:<'hello'> should satisfy condition:<Uppercase>"

Custom Assertion Classes

FEST-Assert can also "decorate" user-defined assertion classes with the prefix 'assertThat,' resulting in improved readability of test code. The only condition is that user-defined assertion classes must implement the marker interface org.fest.assertions.AssertExtension.

The following example demonstrates an assertion class that verifies the state of a ServerSocket:

public class ServerSocketAssertion implements AssertExtension {
  private final ServerSocket socket;

  public ServerSocketAssertion(ServerSocket socket) {
    this.socket = socket;
  }

  public ServerSocketAssert isConnectedTo(int port) {
    assertThat(socket.isBound()).isTrue();
    assertThat(socket.getLocalPort()).isEqualTo(port);
    assertThat(socket.isClosed()).isFalse();
    return this;
  }
}

We can decorate that assertion class with 'assertThat':

ServerSocketAssertion socket = new ServerSocketAssertion(server.getSocket());
assertThat(socket).isConnectedTo(2000);