Search code examples
javaassertj

Assertion of Particular Exception which contains a field


Currently I have a test which tries to check a particular exception which looks like this:

assertThatExceptionOfType(DataIntegrityViolationException.class).isThrownBy(
        () -> xrepo.save(abc))
    .withCauseExactlyInstanceOf(ConstraintViolationException.class);

The exception ConstraintViolationException has a field constraintName available via getter getConstraintName() but I haven't found a way to check that via assertj.

I could imagine something like the following:

assertThatExceptionOfType(DataIntegrityViolationException.class).isThrownBy(
        () -> xrepo.save(abc))
    .withCauseExactlyInstanceOf(ConstraintViolationException.class)
    .with("getConstraintName").isEqualTo("XXXX");

or is there a different way to accomplish this?


Solution

  • May be:

    .extracting(x -> ((ConstraintViolationException)x).getConstraintName())
    .isEqualTo("XXXX");