gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:46:06 25 4
gpt4 key购买 nike

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

编辑:

由于评论不能包含代码,我根据这里的答案放置了我的代码:

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.");
}
}

关于java - 如何检查 Java 类是否包含 JUnit4 测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4838295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com