如何检查Java类是否包含JUnit4测试?

我有一个Java类。 如何检查类是否包含JUnit4测试的方法? 我是否必须使用reflection对所有方法进行迭代,或者JUnit4是否提供此类检查?

编辑:

由于评论不能包含代码,我根据答案放置了我的代码:

private static boolean containsUnitTests(Class clazz) { List methods= new TestClass(clazz).getAnnotatedMethods(Test.class); for (FrameworkMethod eachTestMethod : methods) { List errors = new ArrayList(); eachTestMethod.validatePublicVoidNoArg(false, errors); if (errors.isEmpty()) { return true; } else { throw ExceptionUtils.toUncheked(errors.get(0)); } } return false; } 

使用内置的JUnit 4类org.junit.runners.model.FrameworkMethod来检查方法。

 /** * Get all 'Public', 'Void' , non-static and no-argument methods * in given Class. * * @param clazz * @return Validate methods list */ static List getValidatePublicVoidNoArgMethods(Class clazz) { List result = new ArrayList(); List methods= new TestClass(clazz).getAnnotatedMethods(Test.class); for (FrameworkMethod eachTestMethod : methods){ List errors = new ArrayList(); eachTestMethod.validatePublicVoidNoArg(false, errors); if (errors.isEmpty()) { result.add(eachTestMethod.getMethod()); } } return result; } 

假设您的问题可以重新表述为“如何检查类是否包含带有org.junit.Test注释的方法?” ,然后使用Method#isAnnotationPresent() 。 这是一个启动示例:

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

JUnit通常使用基于注释的方法或通过扩展TestCase进行配置。 在后一种情况下,我将使用reflection来查找已实现的接口( object.getClass().getInterfaces() )。 在前一种情况下,我将迭代所有寻找@Test注释的方法,例如,

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