Summary
It would be nice if the assertThatCode().doesNotThrowException() API would be able execute functions that return a value and then return that value for further inspection.
This would make it easy to provide a nice description to an otherwise maybe nondescript exception that is thrown.
Example
@Test
public void intendedApi() {
int x = assertThatCode(this::doStuff)
.describedAs("doing things")
.doesNotThrowAnyException();
assertThat(x).isEqualTo(3);
}
@Test
public void currentSolution1() {
int x;
try {
x = doStuff();
} catch (Exception e) {
fail("doing things");
return; // never reached; needed because fail() is not recognized by the java compiler as method exit
}
assertThat(x).isEqualTo(3);
}
@Test
public void currentSolution2() {
AtomicReference<Integer> x = new AtomicReference<>();
assertThatCode(() -> x.set(doStuff()))
.describedAs("doing things")
.doesNotThrowAnyException();
assertThat(x.get()).isEqualTo(3);
}
// utility for demonstration purposes
public int doStuff() throws Exception {
if (new Random().nextBoolean()) {
throw new Exception();
}
return 3;
}
Summary
It would be nice if the
assertThatCode().doesNotThrowException()API would be able execute functions that return a value and then return that value for further inspection.This would make it easy to provide a nice description to an otherwise maybe nondescript exception that is thrown.
Example