Make BrambleTestCase fail if background thread throws an exception

This commit is contained in:
Sebastian Kürten
2022-02-07 17:26:26 +01:00
parent 58a122ee28
commit e3f2a30120
2 changed files with 21 additions and 3 deletions

View File

@@ -1,17 +1,34 @@
package org.briarproject.bramble.test; package org.briarproject.bramble.test;
import org.junit.After;
import org.junit.Before;
import java.lang.Thread.UncaughtExceptionHandler; import java.lang.Thread.UncaughtExceptionHandler;
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;
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(); throwable.printStackTrace();
fail(); exceptionInBackgroundThread = true;
}; };
Thread.setDefaultUncaughtExceptionHandler(fail); Thread.setDefaultUncaughtExceptionHandler(fail);
} }
@Before
public void before() {
exceptionInBackgroundThread = false;
}
@After
public void after() {
if (exceptionInBackgroundThread) {
fail("background thread has thrown an exception");
}
}
} }

View File

@@ -12,7 +12,7 @@ public class ThreadExceptionTest extends BrambleTestCase {
fail(); fail();
} }
@Test(expected = AssertionError.class) @Test
public void testExceptionInThreadMakesTestCaseFail() { public void testExceptionInThreadMakesTestCaseFail() {
Thread t = new Thread(() -> { Thread t = new Thread(() -> {
System.out.println("thread before exception"); System.out.println("thread before exception");
@@ -24,7 +24,8 @@ public class ThreadExceptionTest extends BrambleTestCase {
t.join(); t.join();
System.out.println("joined thread"); System.out.println("joined thread");
} catch (InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); System.out.println("interrupted while joining thread");
fail();
} }
} }