如何检查 Java 类是否包含 JUnit4 测试?

2023-12-03

我有一个Java课程。如何检查该类是否包含 JUnit4 测试的方法?我是否必须使用反射对所有方法进行迭代,或者 JUnit4 是否提供这样的检查?

Edit:

由于注释不能包含代码,因此我根据此处的答案放置了代码:

private static boolean containsUnitTests(Class<?> clazz) 
{
        List<FrameworkMethod> methods= new TestClass(clazz).getAnnotatedMethods(Test.class);
        for (FrameworkMethod eachTestMethod : methods)
        {
            List<Throwable> errors = new ArrayList<Throwable>();
            eachTestMethod.validatePublicVoidNoArg(false, errors);
            if (errors.isEmpty()) 
            {
                return true;
            }
            else
            {
                throw ExceptionUtils.toUncheked(errors.get(0));
            }
        }
        return false;
}

假设你的问题可以重新表述为“我如何检查该类是否包含方法org.junit.Test注解?”,然后使用Method#isAnnotationPresent()。这是一个启动示例:

for (Method method : Foo.class.getDeclaredMethods()) {
    if (method.isAnnotationPresent(org.junit.Test.class)) {
        System.out.println("Method " + method + " has junit @Test annotation.");
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何检查 Java 类是否包含 JUnit4 测试? 的相关文章

随机推荐