Search code examples
assertj

Custom assertThatThrownBy


after reading this article I was sure to write my own Assertions but I failed. :-(

We have an interface which looks like this:

public class ApplicationException extends RuntimeException {
    public String enhancedStatus() {
        return getClass().getSimpleName();
    }
}

I wrote my own EnhancedStatusAssert like described in the artile.

public class EnhancedStatusAssert extends AbstractAssert<EnhancedStatusAssert, ApplicationException> {

    public EnhancedStatusAssert(ApplicationException actual) {
        super(actual, EnhancedStatusAssert.class);
    }

public static EnhancedStatusAssert assertThat(ApplicationException actual) {
    return new EnhancedStatusAssert(actual);
}

    public EnhancedStatusAssert hasEnhancedCause(String enhancedStatus) {
        isNotNull();

        // check condition
        if (!actual.enhancedStatus().equals(enhancedStatus)) {
            failWithMessage("Expected enhanced status to be <%s> but was <%s>", enhancedStatus, actual.enhancedStatus());
        }

        return this;
    }
}

Which works fine but then I have trouble to override assertThatThrownBy

assertThatThrownBy(() -> { throw new ApplicationException()})
    .isInstanceOf(ApplicationException.class)
    .hasEnhancedCause("cause");

What is the way to get it to run?

Thanks, Markus


Solution

  • Try using asInstanceOf https://assertj.github.io/doc/#assertj-core-3.13.0-asInstanceOf you can write your own InstanceOfAssertFactory for your ApplicationException.

    If you only have one field to check you can extract it with ... extracting and chain assertions on the extracted value.