3

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?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
khmarbaise
  • 92,914
  • 28
  • 189
  • 235

3 Answers3

3

withCauseExactlyInstanceOf does not change the object under test, but with havingCause() further assertions can be performed on the cause.

Combined with asInstanceOf() and returns(), a type-safe check would be:

assertThatExceptionOfType(DataIntegrityViolationException.class).isThrownBy(
        () -> xrepo.save(abc))
    .havingCause()
    .asInstanceOf(type(ConstraintViolationException.class))
    .returns("XXXX", from(ConstraintViolationException::getConstraintName));

Or without type safety, using isInstanceOf and hasFieldOrPropertyWithValue:

assertThatExceptionOfType(DataIntegrityViolationException.class).isThrownBy(
        () -> xrepo.save(abc))
    .havingCause()
    .isInstanceOf(ConstraintViolationException.class)
    .hasFieldOrPropertyWithValue("getConstraintName", "XXX")
Stefano Cordio
  • 1,687
  • 10
  • 20
2

May be:

.extracting(x -> ((ConstraintViolationException)x).getConstraintName())
.isEqualTo("XXXX");
Eugene
  • 117,005
  • 15
  • 201
  • 306
0

The solution of @Eugene brought me to the direction:

assertThatExceptionOfType(DataIntegrityViolationException.class).isThrownBy(
        () -> xyrepository.save(xxx))
    .withCauseExactlyInstanceOf(ConstraintViolationException.class)
    .extracting(s -> ((ConstraintViolationException) (s.getCause())).getConstraintName())
    .isEqualTo("XXXX");

The solution of @StefanoCordio looks also fine...

khmarbaise
  • 92,914
  • 28
  • 189
  • 235