I am using AssertThrows to test for an exception thrown in a thread. I know an exception is thrown since the exception message shows before the AssertionFail message.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class Main {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(1);
SingleThread thread = new SingleThread();
pool.execute(thread);//Thread 1 (in real application there are several)
}
}
class SingleThread implements Runnable{
@Override
public void run() {
throw new NullPointerException();
}
}
class Testing{
@Test
public void SingleThreadTest() {
SingleThread testClass = new SingleThread();
ExecutorService executor = Executors.newCachedThreadPool();
executor.execute(testClass);
Assertions.assertThrows(NullPointerException.class, () -> executor.execute(testClass));
}
}
It appears that JUnit does not see the exception since it is not thrown on the main thread. Is it possible for JUnit detect the exception in this situation?