【发布时间】:2018-01-27 07:58:33
【问题描述】:
目前,每当我需要响应另一个线程中抛出的异常而使测试失败时,我都会编写如下内容:
package com.example;
import java.util.ArrayList;
import java.util.List;
import org.testng.annotations.Test;
import static java.util.Arrays.asList;
import static java.util.Collections.synchronizedList;
import static org.testng.Assert.fail;
public final class T {
@Test
public void testFailureFromLambda() throws Throwable {
final List<Throwable> errors = synchronizedList(new ArrayList<>());
asList("0", "1", "2").parallelStream().forEach(s -> {
try {
/*
* The actual code under test here.
*/
throw new Exception("Error " + s);
} catch (final Throwable t) {
errors.add(t);
}
});
if (!errors.isEmpty()) {
errors.forEach(Throwable::printStackTrace);
final Throwable firstError = errors.iterator().next();
fail(firstError.getMessage(), firstError);
}
}
}
同步列表可以替换为AtomicReference<Throwable>,但通常代码几乎相同。
是否有任何标准(并且不那么冗长)的方法可以使用 Java 中提供的任何测试框架(TestNG、JUnit、Hamcrest、AssertJ 等.)?
【问题讨论】:
标签: unit-testing junit testng hamcrest assertj