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;
}
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.,Assuming that your question can be reformulated as "How can I check if the class contains methods with
org.junit.Test
annotation?", then useMethod#isAnnotationPresent()
. Here's a kickoff example:Use built-in JUnit 4 class org.junit.runners.model.FrameworkMethod to check methods.