0

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?

jlaufer
  • 89
  • 8
  • 2
    I would "unit test" the code that runs the "runnable" instead. – Pam Stums Aug 04 '22 at 19:11
  • Or, if there is a "side effect" to the exception that you can detect, then you can assert that side effect status instead. For example, if due to the exception some variable becomes null.. you can asset that in your test. – Pam Stums Aug 04 '22 at 19:13
  • From your example it does not seem to bring any benefit in adding another layer of compexity by using an `ExecutorService` instead of just running the `Runnable` on it's own. – asbachb Aug 04 '22 at 19:14
  • 1
    [How to catch an Exception from a thread](https://stackoverflow.com/questions/6546193/how-to-catch-an-exception-from-a-thread) – rgettman Aug 04 '22 at 19:18

0 Answers0