title: How do I test this method's expected behavior in Java: it spawn a thread, and throws an exception under certain conditions
body: <p>Suppose that I have a method which spawns a new thread and do some work. Under certain conditions, the newly spawn thread would throw a certain type of exception, which terminates the entire process. I would like to write JUnit tests to verify this behavior. Is there a way to do it?</p>
  
  <p>The method is:</p>
  
  <pre><code>private void foo() {
    new Thread() {
      @Override void run() {
        throw new CertainException("exception messages");
      }
    }.start();
  }
  </code></pre>
  
  <p>In test (conceptually):</p>
  
  <pre><code>public testExceptionThrownFromNewThread() throws Exception {
    try {
      foo();
      Thread.sleep(5000);  // wait for the exception to be thrown
      fail();
    } catch (CertainException e) {
      assertEquals(e.message, "exception messages");
    }
  }
  </code></pre>
  
  <p>This test doesn't work because the exception spawn from the other thread cannot be caught.</p>