Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You could overwrite the default <code>UncaughtExceptionHandler</code> for Threads. It gets called whenever a Thread throws an exception. In this handler, you can check whether the expected exception is equal to the thrown exception and e.g. test for messages or count the occurences of the exception. By using a <code>CountDownLatch</code>, you can also check whether the exceptions are thrown in time and how many of them you expect.</p> <p>This works even if you do not have access to the <code>Thread</code> created by the class under test. If you have access to it though, there is certainly an easier approach, e.g. refactoring the class under test and introduce an Exception Listener or alike. Make the class under test better testable also improves the design, e.g. by removing the dependency on Threads and directly test the body of the run() method which you could externalize.</p> <pre><code>public class ThreadExceptionTest { private void foo() { new Thread(new Runnable() { @Override public void run() { throw new RuntimeException("exception messages"); } }).start(); } @Test public void testFoo() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final RuntimeException expectedException = new RuntimeException("exception messages"); UncaughtExceptionHandler eh = new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { if (e.getMessage().equals(expectedException.getMessage())) latch.countDown(); } }; Thread.setDefaultUncaughtExceptionHandler(eh); foo(); assertTrue(latch.await(100,TimeUnit.MILLISECONDS)); } </code></pre> <p>}</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload