How to check if a Java class contains JUnit4 tests?

六月ゝ 毕业季﹏ 提交于 2019-12-04 05:08:33

问题


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?

Edit:

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;
}

回答1:


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;
}



回答2:


Assuming that your question can be reformulated as "How can I check if the class contains methods with org.junit.Test annotation?", then use Method#isAnnotationPresent(). Here's a kickoff example:

for (Method method : Foo.class.getDeclaredMethods()) {
    if (method.isAnnotationPresent(org.junit.Test.class)) {
        System.out.println("Method " + method + " has junit @Test annotation.");
    }
}



回答3:


JUnit is commonly configured using either an annotation based approach or by extending TestCase. In the latter case I would use reflection to look for implemented interfaces (object.getClass().getInterfaces()). In the former case I would iterate all methods looking for @Test annotations, e.g.,

Object object; // The object to examine
for (Method method : object.getClass().getDeclaredMethods()) {
    Annotation a = method.getAnnotation(Test.class);
    if (a != null) {
        // found JUnit test
    }
}


来源:https://stackoverflow.com/questions/4838295/how-to-check-if-a-java-class-contains-junit4-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!