AssertJ 断言异常抛出或结果
AssertJ assert either exception thrown or result
我有一个测试用例,我正在使用执行程序服务并调用多个可调用线程。这些线程可能会导致调用成功或可能会出现异常(这是预期的行为)。
我需要断言未来的对象要么抛出异常,要么 return 正确响应。
for(Future<Resp> future : futureList) {
Assertions.assertThatThrownBy(() ->
futureResponse.get()).isInstanceOf(ExecutionException.class);
// or
Assertions.assertThat(futureResponse.get()).isEqualTo(RespObj);
}
如何断言此 "OR" 行为?
您可以使用 try catch
块:
for(Future<Resp> future : futureList) {
try {
Assertions.assertThat(futureResponse.get()).isEqualTo(RespObj);
} catch (Throwable e) {
Assertions.assertThat(e).isInstanceOf(ExecutionException.class);
}
}
如果是 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)
}
}
我有一个测试用例,我正在使用执行程序服务并调用多个可调用线程。这些线程可能会导致调用成功或可能会出现异常(这是预期的行为)。 我需要断言未来的对象要么抛出异常,要么 return 正确响应。
for(Future<Resp> future : futureList) {
Assertions.assertThatThrownBy(() ->
futureResponse.get()).isInstanceOf(ExecutionException.class);
// or
Assertions.assertThat(futureResponse.get()).isEqualTo(RespObj);
}
如何断言此 "OR" 行为?
您可以使用 try catch
块:
for(Future<Resp> future : futureList) {
try {
Assertions.assertThat(futureResponse.get()).isEqualTo(RespObj);
} catch (Throwable e) {
Assertions.assertThat(e).isInstanceOf(ExecutionException.class);
}
}
如果是 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)
}
}