我有一个 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/