Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assertThrows multiple exceptions

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

like image 282
Xbreizh Avatar asked Jul 31 '26 10:07

Xbreizh


1 Answers

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.

like image 70
JB Nizet Avatar answered Aug 03 '26 01:08

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!