0

I am trying test if RunTimeException thrown from thread is added into the System.err. But even after waiting for 1 min it is not found into System.err Following is code piece

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);
  }
}

Can someone please point out possible mistake in the test?

1 Answers1

0

Update your Runnable implementation to

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

you can also use

System.err.print("exception");

to

 e.printStackTrace();

You should do this like this because SystemErrRule intercepts the writes to System.err. printStackTrace() can do it for you or you can do it manually by using System.err

Planck Constant
  • 1,406
  • 1
  • 17
  • 19