testdriven.com Wrangling quality out of chaos

FEST-Assert: Another “assertThat” library for testing

09.20.2007 · Posted in Java

FEST-Assert is another "assertThat" library that aims at making tests more readable. Here is an example:

Code:
import static org.fest.assertions.Assertions.assertThat;
import org.testng.annotations.Test;

public class SomeTest {
@Test public void testApp() {
assertThat(true).isTrue();
int result = 2 + 3;
assertThat(result).as("calculation").isEqualTo(5);
assertThat("Hello World").contains("World");
}
}

We like this approach because:

1. Only one static import is needed (org.fest.assertions.Assertions.assertThat)

2. Allows us to use our IDE’s "auto-complete" feature: we only type "." and we get the possible assertion methods for the value passed to "assertThat"

3. We can chain related assertion methods:

Code:
assertThat(yoda).isInstanceOf(Jedi.class).isEqualTo(foundJedi).isNotEqualTo(possibleSith);

FEST-Assert can also be extended using Conditions. The following condition verifies that the characters in a String are in uppercase:

Code:
class UpperCaseCondition extends Condition<String> {

private UpperCaseCondition(String description) {
super(description);
}

@Override 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:

Code:
assertThat("hello").as("Greeting").satisfies(isUpperCase());

which will fail with the message "[Greeting] expected:Uppercase but was:<’hello’>"

We would appreciate any feedback.

FEST project page.

  • del.icio.us
  • Digg
  • Google Bookmarks
  • Slashdot
  • StumbleUpon
  • Technorati
  • Twitter

Comments are closed