AssertJ断言抛出异常或结果

时间:2018-01-31 07:23:38

标签: java junit future assertions assertj

我有一个测试用例,我正在使用执行程序服务并调用许多可调用线程。这些线程可能导致成功调用或可能发出异常(这是预期的行为)。 我需要断言未来的对象要么抛出异常,要么返回正确的响应。

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

我如何断言这个&#34; OR&#34;行为?

2 个答案:

答案 0 :(得分:2)

您可以使用try catch阻止:

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

答案 1 :(得分:1)

如果是ExecutionException,您可能需要检查其原因。

    for (Future<Resp> future : futureList) {
        try {
            Resp got = future.get();
            assertValidResp(got); // check normal behavior (eg not null)
        }
        catch (ExecutionException e) {
            Throwable cause = e.getCause();
            assertAcceptedException(cause); // check for expected abnormal behavior (eg instanceof check)
        }
    }