fest-assert-2.x
fest-assert-2.x copied to clipboard
Make custom assertions easier to write
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).
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.