JUnit测试中如何捕获应用内Thread.sleep抛出的InterruptedException
可行实现方案(无需修改原有异常抛出层级)
方案1:捕获System.err输出验证异常栈
现有代码会将InterruptedException的栈信息打印到标准错误流,测试时临时替换System.err的输出流即可捕获打印内容做断言:
@Test public void testInterruptedExceptionCaught() throws Exception { // 保存原始的System.err PrintStream originalErr = System.err; ByteArrayOutputStream baos = new ByteArrayOutputStream(); System.setErr(new PrintStream(baos)); try { // 执行原有超时调用逻辑 executor.invokeAll(callables, 2, TimeUnit.SECONDS); // 等待任务执行完成 executor.shutdown(); executor.awaitTermination(3, TimeUnit.SECONDS); // 验证输出中包含预期异常 String errContent = baos.toString(); assertThat(errContent).contains("java.lang.InterruptedException: sleep interrupted") .contains("com.blah.myapp.FooJob.work()"); } finally { // 恢复原始System.err,避免影响其他测试 System.setErr(originalErr); } }
方案2:新增无侵入测试钩子
可以在不改动原有异常抛出逻辑的前提下,给FooJob加一个仅测试用的异常存储字段,测试时直接读取验证:
业务代码修改(完全不影响原有逻辑,仅新增存储):
class FooJob { // 仅测试用,存储最近捕获的中断异常,可设为private通过反射读取 private InterruptedException lastInterruptedException; public String work() { try { Thread.sleep(10000); } catch (InterruptedException e) { lastInterruptedException = e; e.printStackTrace(); } return "1"; } }
测试代码:
@Test public void testInterruptedExceptionCaught() throws Exception { FooJob job = new FooJob(); // 组装callables执行原有超时调用逻辑 executor.invokeAll(callables, 2, TimeUnit.SECONDS); executor.shutdown(); executor.awaitTermination(3, TimeUnit.SECONDS); // 断言异常存在,也可进一步校验异常属性 Field field = FooJob.class.getDeclaredField("lastInterruptedException"); field.setAccessible(true); InterruptedException caughtEx = (InterruptedException) field.get(job); assertThat(caughtEx).isNotNull(); }
如果不想给业务类加任何额外代码,可使用PowerMock拦截Thread.sleep方法的异常抛出,在测试侧直接记录异常实例做断言。
内容的提问来源于stack exchange,提问作者user63898
相关产品推荐
相关产品推荐

