Include background exception in test failure report.

This commit is contained in:
akwizgran
2022-03-28 14:59:01 +01:00
parent 32b62d3e30
commit 288f3331ec
2 changed files with 14 additions and 9 deletions

View File

@@ -7,34 +7,39 @@ import java.lang.Thread.UncaughtExceptionHandler;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import javax.annotation.Nullable;
import static java.util.logging.Logger.getLogger; import static java.util.logging.Logger.getLogger;
import static org.junit.Assert.fail;
public abstract class BrambleTestCase { public abstract class BrambleTestCase {
private static final Logger LOG = private static final Logger LOG =
getLogger(BrambleTestCase.class.getName()); getLogger(BrambleTestCase.class.getName());
protected volatile boolean exceptionInBackgroundThread = false; @Nullable
protected volatile Throwable exceptionInBackgroundThread = null;
public BrambleTestCase() { public BrambleTestCase() {
// Ensure exceptions thrown on worker threads cause tests to fail // Ensure exceptions thrown on worker threads cause tests to fail
UncaughtExceptionHandler fail = (thread, throwable) -> { UncaughtExceptionHandler fail = (thread, throwable) -> {
LOG.log(Level.WARNING, "Caught unhandled exception", throwable); LOG.log(Level.WARNING, "Caught unhandled exception", throwable);
exceptionInBackgroundThread = true; exceptionInBackgroundThread = throwable;
}; };
Thread.setDefaultUncaughtExceptionHandler(fail); Thread.setDefaultUncaughtExceptionHandler(fail);
} }
@Before @Before
public void beforeBrambleTestCase() { public void beforeBrambleTestCase() {
exceptionInBackgroundThread = false; exceptionInBackgroundThread = null;
} }
@After @After
public void afterBrambleTestCase() { public void afterBrambleTestCase() {
if (exceptionInBackgroundThread) { Throwable thrown = exceptionInBackgroundThread;
fail("background thread has thrown an exception unexpectedly"); if (thrown != null) {
throw new AssertionError(
"background thread has thrown an exception unexpectedly",
thrown);
} }
} }
} }

View File

@@ -1,8 +1,8 @@
package org.briarproject.bramble.test; package org.briarproject.bramble.test;
import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public class ThreadExceptionTest extends BrambleTestCase { public class ThreadExceptionTest extends BrambleTestCase {
@@ -29,8 +29,8 @@ public class ThreadExceptionTest extends BrambleTestCase {
fail(); fail();
} }
Assert.assertTrue(exceptionInBackgroundThread); assertNotNull(exceptionInBackgroundThread);
exceptionInBackgroundThread = false; exceptionInBackgroundThread = null;
} }
} }