Allow BrambleTestCase to handle background thread exceptions gracefully during after()

This commit is contained in:
Sebastian Kürten
2022-03-04 07:57:50 +01:00
parent e3f2a30120
commit 32b62d3e30
2 changed files with 15 additions and 6 deletions

View File

@@ -4,31 +4,37 @@ import org.junit.After;
import org.junit.Before; import org.junit.Before;
import java.lang.Thread.UncaughtExceptionHandler; import java.lang.Thread.UncaughtExceptionHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import static java.util.logging.Logger.getLogger;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public abstract class BrambleTestCase { public abstract class BrambleTestCase {
private volatile boolean exceptionInBackgroundThread = false; private static final Logger LOG =
getLogger(BrambleTestCase.class.getName());
protected volatile boolean exceptionInBackgroundThread = false;
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) -> {
throwable.printStackTrace(); LOG.log(Level.WARNING, "Caught unhandled exception", throwable);
exceptionInBackgroundThread = true; exceptionInBackgroundThread = true;
}; };
Thread.setDefaultUncaughtExceptionHandler(fail); Thread.setDefaultUncaughtExceptionHandler(fail);
} }
@Before @Before
public void before() { public void beforeBrambleTestCase() {
exceptionInBackgroundThread = false; exceptionInBackgroundThread = false;
} }
@After @After
public void after() { public void afterBrambleTestCase() {
if (exceptionInBackgroundThread) { if (exceptionInBackgroundThread) {
fail("background thread has thrown an exception"); fail("background thread has thrown an exception unexpectedly");
} }
} }
} }

View File

@@ -1,5 +1,6 @@
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.fail; import static org.junit.Assert.fail;
@@ -27,7 +28,9 @@ public class ThreadExceptionTest extends BrambleTestCase {
System.out.println("interrupted while joining thread"); System.out.println("interrupted while joining thread");
fail(); fail();
} }
Assert.assertTrue(exceptionInBackgroundThread);
exceptionInBackgroundThread = false;
} }
} }