JUnit框架仅捕获运行测试的主线程中的断言错误。它不知道新的派生线程中的异常。为了正确执行此操作,您应该将线程的终止状态传达给主线程。您应该正确同步线程,并使用某种共享变量来指示嵌套线程的结果。
编辑:
这是可以提供帮助的通用解决方案:
class AsynchTester{ private Thread thread; private AssertionError exc; public AsynchTester(final Runnable runnable){ thread = new Thread(new Runnable(){ public void run(){ try{ runnable.run(); }catch(AssertionError e){ exc = e; } } }); } public void start(){ thread.start(); } public void test() throws InterruptedException{ thread.join(); if (exc != null) throw exc; }}您应该在构造函数中将其传递给runnable,然后只需调用start()进行激活,然后调用test()进行验证。测试方法将在必要时等待,并将在主线程的上下文中引发断言错误。



