How to check if a Java class contains JUnit4 tests

2019-03-02 08:36发布

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

3条回答
一夜七次
2楼-- · 2019-03-02 09:19

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
    }
}
查看更多
倾城 Initia
3楼-- · 2019-03-02 09:36

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.");
    }
}
查看更多
▲ chillily
4楼-- · 2019-03-02 09:41

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;
}
查看更多
登录 后发表回答