Search code examples
javajunitfutureassertionsassertj

AssertJ assert either exception thrown or result


I have a test case where i am using an executor service and invoking a number of callable threads. These threads may result in a successful call or may give an exception(which is an expected behavior). I need to assert that the future objects either throw an exception or return correct response.

for(Future<Resp> future : futureList) {
Assertions.assertThatThrownBy(() -> 
futureResponse.get()).isInstanceOf(ExecutionException.class);
// or
Assertions.assertThat(futureResponse.get()).isEqualTo(RespObj);
}

How do I assert this "OR" behavior?


Solution

  • You can use try catch block:

      for(Future<Resp> future : futureList) {
            try {
                Assertions.assertThat(futureResponse.get()).isEqualTo(RespObj);
            } catch (Throwable e) {
                Assertions.assertThat(e).isInstanceOf(ExecutionException.class);
            }
        }