AssertJ combine exception catching and return type assertions

100 Views Asked by At

I have a method which catches an IOException while trying to process a JSON file and if this exception occurs false is being returned. Something like:

public boolean method(){
 try{
  // process json file
   return true;
 } catch IOException {
   // write stuff into db
   return false;
 }
}

The catch block writes exception message to the database. So given a method with a boolean return type and exception handling how can I combine both in my unit test to assert the instance of the exception/its message and method's return value? I am aware of

Assertions.assertThatThrownBy(() -> objectUnderTest.method()).isInstanceOf(IOException.class)

The above statement results in: java.lang.AssertionError: Expecting code to raise a throwable.

and

Assertions.assertThat(objectUnderTest.method()).isFalse() // works well
1

There are 1 best solutions below

0
Stefano Cordio On BEST ANSWER

As the exception is caught in the method, AssertJ has no chance to see it, hence the assertion error you already experienced.

Assuming you are in a unit test with a mock of the DB writer, you might intercept that call of the mock and assert the invocation parameter(s).

If you aren't in a unit test, you should read back from the DB and assert its content.