Consider I have a method to test, which
- may have side-effects (like files created on the file system), and
- may throw an exception.
Some of the side effects can be observed (and tested) even when the exception is thrown. My sample test code is below:
final SoftAssertions softly = new SoftAssertions();
try {
/*
* May throw an exception
*/
doSmth();
} catch (final IOException ioe) {
/*
* How do I add a soft assertion wrapping an exception?
*/
}
/*
* Testing for side effects.
*/
softly.assertThat(...).as("%s exit code", ...).isEqualTo(0);
softly.assertThat(...).as("the number of downloaded files").isEqualTo(3);
softly.assertThat(...).as("this should be true").isTrue();
softly.assertThat(...).as("and this should be true, too").isTrue();
softly.assertAll();
Question 1
What is the best way to create yet another soft assertion out of the exception thrown? With the raw TestNG API, I could write simply
softly.fail(ioe.toString(), ioe);
but AssertJ doesn't seem to provide anything similar. So far, my best option is adding smth like this to the catch block:
softly.assertThat(true).as(ioe.toString()).isFalse();
Are there any better alternatives?
Question 2
How do I make exception(s) thrown by my code being tested, appear as a cause (or suppressed exceptions) of the resulting AssertionError
? Currently, I do the following:
Throwable failure = null;
try {
doSmth();
} catch (final IOException ioe) {
failure = ioe;
}
try {
softly.assertAll();
} catch (final AssertionError ae) {
if (failure != null) {
if (ae.getCause() == null) {
ae.initCause(failure);
} else {
ae.addSuppressed(failure);
}
}
throw ae;
}
-- but a more elegant version is much appreciated.