本文介绍了如何检查Java类是否包含JUnit4测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Java类。如何检查类是否包含JUnit4测试的方法?我是否必须使用反射对所有方法进行迭代,或者JUnit4是否提供这样的检查?
I have a Java class. How can I check if the class contains methods that are JUnit4 tests? Do I have to do an iteration on all methods using reflection, or does JUnit4 supply such a check?
编辑:
由于评论不能包含代码,我根据答案放置了我的代码:
since comments cannot contain code, I placed my code based on the answer here:
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;
}
推荐答案
使用内置JUnit 4 class org.junit.runners.model.FrameworkMethod 来检查方法。
Use built-in JUnit 4 class org.junit.runners.model.FrameworkMethod to check methods.
/**
* Get all 'Public', 'Void' , non-static and no-argument methods
* in given Class.
*
* @param clazz
* @return Validate methods list
*/
static List<Method> getValidatePublicVoidNoArgMethods(Class clazz) {
List<Method> result = new ArrayList<Method>();
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()) {
result.add(eachTestMethod.getMethod());
}
}
return result;
}
这篇关于如何检查Java类是否包含JUnit4测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!