Runtime Exception从线程未登录到Systemerrrule中



我正在尝试测试如果从线程中抛出的RuntimeException是否添加到System.err中。但是即使等待了1分钟,也找不到系统。以下是代码

public class TestTest {
  @Rule public SystemErrRule errRule = new SystemErrRule().enableLog();
  @org.junit.Test
  public void testLogging(){
    ExecutorRunner.submitTask(new Runnable() {
      @Override public void run() {
        throw new RuntimeException("exception");
      }
    });
Awaitility.await().atMost(60l, TimeUnit.SECONDS).until(new Callable<Boolean>() {
  @Override public Boolean call() throws Exception {
    return errRule.getLog().contains("exception");
  }
});
System.out.println("TestTest.testLogging :: " + "errLog: "+errRule.getLog());
assertTrue(errRule.getLog().contains("exception"));

}
  @After
  public void checkException(){
    System.out.println("TestTest.checkException :: " + "checkin log");
  }
}
class ExecutorRunner{
  static final ExecutorService execService = Executors
    .newCachedThreadPool(new ThreadFactory() {
      AtomicInteger threadNum = new AtomicInteger();
      public Thread newThread(final Runnable r) {
        Thread result = new Thread(r, "Function Execution Thread-"
          + threadNum.incrementAndGet());
        result.setDaemon(true);
        return result;
      }
    });
  static void submitTask(Runnable task) {
    execService.submit(task);
  }
}

有人可以指出测试中可能的错误吗?

将可运行的实现更新为

    ExecutorRunner.submitTask(new Runnable() {
        @Override
        public void run() {
            try {
                throw new RuntimeException("exception");
            } catch (RuntimeException e) {
                System.err.print("exception");
            }  
        }
    });

您也可以使用

System.err.print("exception");

to

 e.printStackTrace();

您应该这样做,因为Systemerrrule拦截了写信给System.err。printstacktrace()可以为您做到这一点,也可以使用System.err

手动执行此操作。

相关内容

  • 没有找到相关文章

最新更新