以下のコード例では、testMethod() が main() 経由で実行される場合は期待どおりに動作しますが、JUNIT 経由で実行される場合は MyUncaughtExceptionHandler が呼び出されません。
これについて何か説明はありますか?
package nz.co.test;
import java.lang.Thread.UncaughtExceptionHandler;
import org.junit.Test;
public class ThreadDemo {
private void testMethod() {
Thread.currentThread().setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
Object b = null;
// Cause a NPE
b.hashCode();
}
@Test
public void testJunit() {
// Run via JUnit and MyUncaughtExceptionHandler doesn't catch the Exception
testMethod();
}
public static void main(String[] args) {
// Run via main() works as expected
new ThreadDemo().testMethod();
}
static class MyUncaughtExceptionHandler implements UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("I caught the exception");
}
}
}