小编Rob*_*ave的帖子

Java Thread.currentThread().setUncaughtExceptionHandler()不能使用JUNIT?

在下面的示例代码中,如果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");
    } …
Run Code Online (Sandbox Code Playgroud)

java junit

7
推荐指数
2
解决办法
2445
查看次数

标签 统计

java ×1

junit ×1