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