基于反射实现JUnit单元测试时输出为空的问题求助
问题成因
- 无限递归死循环:
execute方法内部第一行写了execute(Reflection.class),调用该方法时会直接进入自调用的死循环,永远无法执行后续的测试扫描逻辑,极端情况会触发栈溢出报错。 - 缺少程序启动入口:Java程序必须以
main方法作为执行入口,当前两个类都没有定义main方法,运行后不会触发任何逻辑,自然没有输出。 - 废弃API风险(可选优化):
Class.newInstance()在Java 9及以上版本已被标记为废弃,处理异常场景的能力较弱,推荐替换为构造器实例化方案。
修复方案
- 直接删除
execute方法中多余的递归调用语句execute(Reflection.class); - 新增
main方法作为程序入口,完成测试类实例化、执行测试、打印结果的全流程逻辑 - (可选)替换废弃的实例化API,兼容更高版本JDK的规范
修复后代码
SimpleUnitTester.java
import java.lang.reflect.Method; public class SimpleUnitTester { public int execute(Class clazz) throws Exception { int failedCount = 0; Reflection reflection = null; try { // 替换废弃API,兼容高版本JDK reflection = (Reflection) clazz.getDeclaredConstructor().newInstance(); } catch (Exception e) { e.printStackTrace(); // 实例化失败直接返回,避免后续空指针 return failedCount; } Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { if (method.getName().startsWith("test") && method.getReturnType() == boolean.class) { try { boolean returnedValue = (Boolean) method.invoke(reflection); if (!returnedValue) { failedCount++; } } catch (Exception e) { e.printStackTrace(); } } } return failedCount; } // 新增main方法作为启动入口 public static void main(String[] args) throws Exception { SimpleUnitTester tester = new SimpleUnitTester(); int failed = tester.execute(Reflection.class); System.out.println("失败用例总数:" + failed); } }
运行结果
测试目标类无需修改,运行后输出结果为:
失败用例总数:2
内容的提问来源于stack exchange,提问作者Abhinav Raj
相关产品推荐
相关产品推荐

