我正在尝试测试是否将从线程抛出的RunTimeException添加到System.err中。 但即使等待1分钟后,也无法进入System.err 以下是代码
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);
}
}
有人可以指出测试中可能存在的错误吗?
答案 0 :(得分:0)
将Runnable实现更新为
ExecutorRunner.submitTask(new Runnable() {
@Override
public void run() {
try {
throw new RuntimeException("exception");
} catch (RuntimeException e) {
System.err.print("exception");
}
}
});
您也可以使用
System.err.print("exception");
到
e.printStackTrace();
您应该这样做,因为SystemErrRule拦截对System.err的写入。 printStackTrace()可以为您完成,也可以使用System.err
手动完成