5

Can anyone tell me how to use assertThrows with several exceptions?

for ex, here is a class:

 protected void checkViolation(Set<ConstraintViolation<EcritureComptable>> vViolations) throws FunctionalException {
    if (!vViolations.isEmpty()) {
        throw new FunctionalException("L'écriture comptable ne respecte pas les règles de gestion.",
                                      new ConstraintViolationException(
                                          "L'écriture comptable ne respecte pas les contraintes de validation",
                                          vViolations));
    }
}

and my testing method:

 @Test
void checkViolation(){
    comptabiliteManager = spy(ComptabiliteManagerImpl.class);
    when(vViolations.isEmpty()).thenReturn(false);

    assertThrows(  ConstraintViolationException.class, () ->comptabiliteManager.checkViolation(vViolations), "a string should be provided!");
}

I would like to match the method and throw ConstraintViolationException and FunctionalException altogether

Any idea?

Thanks

Xbreizh
  • 333
  • 4
  • 19

2 Answers2

5

A single exception is thrown, and it's of type FunctionalException. The cause of this FunctionalException is a ConstraintViolationException.

Assuming assertThrows is the JUnit 5 method, it returns the thrown exception. So you can simply get its cause and add additional checks on this cause.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
2

I assume that ConstraintViolationException will be the root cause of FunctionalException. In this case to check that thrown exception has desired cause you can do something like

Executable executable = () -> comptabiliteManager.checkViolation(vViolations);

Exception exception = assertThrows(FunctionalException.class, executable);

assertTrue(exception.getCause() instanceof ConstraintViolationException);

Another maybe more clean solution would be to use AssertJ and its API.

Throwable throwable = catchThrowable(() -> comptabiliteManager.checkViolation(vViolations));

assertThat(throwable).isInstanceOf(FunctionalException.class)
            .hasCauseInstanceOf(ConstraintViolationException.class);

You would have to import methods from Assertions class from AssertJ :

import static org.assertj.core.api.Assertions.catchThrowable;
import static org.assertj.core.api.Assertions.assertThat;

I encourage you to look at this API because it has many fluent methods.

Michał Krzywański
  • 15,659
  • 4
  • 36
  • 63