[英]How to fail JUnit test from another thread
考虑以下测试代码:
@Test
public void test() throws InterruptedException {
var latch = new CountDownLatch(1);
Executors.newSingleThreadExecutor().execute(() -> {
latch.countDown();
Assert.fail("Doesn't fail the test");
});
latch.await();
}
它打印异常,但通过。
Exception in thread "pool-1-thread-1" java.lang.AssertionError: Doesn't fail the test at org.junit.Assert.fail(Assert.java:89) at MyTest.lambda$test$0(MyTest.java :55) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.基础/java.lang.Thread.run(Thread.java:834)
我试图设置自定义未捕获异常处理程序setUncaughtExceptionHandler((t, e) -> Assert.fail(e.getMessage()))
,但这没有帮助。
您可以使用两个线程都可以访问的外部 state 来执行此操作。 请注意latch.countDown();
应在更改 state 后添加
private volatile boolean failed = false;
@Test
public void test() throws InterruptedException {
var latch = new CountDownLatch(1);
Executors.newSingleThreadExecutor().execute(() -> {
failed = true;//or false depending on the use case
latch.countDown();
});
latch.await();
if(failed){
Assert.fail("Doesn't fail the test");
}
}
您还可以使用 shutdown + awaitTermination 来确保所有任务都已完成,并使用 try-catch 和 AtomicBoolean 来断言没有“内部”引发 AssertionErrors。
AtomicBoolean failed = new AtomicBoolean(false);
ExecutorService executorService = Executors.newFixedThreadPool(PARALLEL_POOL_SIZE);
// start tasks.. maybe in a loop to generate load..
executorService.execute(() -> {
try {
// Test something
// ..
// Validate
assertThat(actual, equalTo(EXPECTED));
} catch (AssertionError e) {
failed.set(true);
throw e;
}
});
executorService.shutdown();
boolean terminatedInTime = executorService.awaitTermination(5, TimeUnit.SECONDS);
assertTrue(terminatedInTime);
assertFalse(failed.get());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.