fest-assert-2.x icon indicating copy to clipboard operation
fest-assert-2.x copied to clipboard

Make custom assertions easier to write

Open joel-costigliola opened this issue 12 years ago • 2 comments

For the time being, writing an assertion in its own assertion class looks like :

  public TolkienCharacterAssert hasAge(int age) {
    // use existing WritableAssertionInfo to set a specific error message
    WritableAssertionInfo info = getWritableAssertionInfo();
    info.overridingErrorMessage(format("Expected character's age to be <%s> but was <%s>", age, actual.getAge()));
    Objects.instance().assertEqual(info, actual.getAge(), age);
    // return the current assertion for method chaining
    return this;
  }

For our users, it's not easy to find that Objects was needed to be called instead of simply throwing an AssertionError directly, reason being to reuse existing WritableAssertionInfo.

I think it should be much simpler to write its own custom assertions.

Points to keep in mind that we should honor the description and the overridden error message set by the user (if any).

joel-costigliola avatar Sep 08 '12 09:09 joel-costigliola

Proposal :

public TolkienCharacterAssert hasAge(int age) {
  // check if the condition to assert is met
  if (actual.getAge() != age) {
    failWithMessage("Expected character's age to be <%s> but was <%s>", age, actual.getAge());
  }
  // return the current assertion for method chaining
  return this;
}

where failWithMessage is defined in AbstractAssert

protected void failWithMessage(String errorMessage, Object... arguments) {
  throw Failures.instance().failure(info, new BasicErrorMessageFactory(errorMessage, arguments));
}

failWithMessage is protected because it is only intended for extending Fest, it respects user description and overriden error message if any.

joel-costigliola avatar Sep 15 '12 16:09 joel-costigliola

For your information, this issue has been fixed in AssertJ a fork of Fest Assert 2.0M10.

joel-costigliola avatar Apr 15 '13 09:04 joel-costigliola