我有一个Java课。如何检查该类是否包含JUnit4测试的方法?我是否必须使用反射对所有方法进行迭代,还是JUnit4提供这种检查?
编辑:
由于注释不能包含代码,因此我根据以下答案放置了代码:
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 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<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; }