动态识别测试 类
Identify test classes dynamically
我需要一个解决方案来从 jar 文件中识别测试 classes 并执行它们。那是我的 Web 应用程序接受一个 jar 文件作为输入并识别 jar 中的测试 classes 和执行它们并显示结果。
目前,每当我尝试从 jar.I 访问 class 文件时,我都遇到 class 未找到异常,认为我需要将外部 jar 文件添加到我的 class 路径?
以下是您可以遵循的一些步骤:
- 获取 Jar 文件路径
- 从中读取 classes
- 遍历那些 classes
- 获取每个 class
的方法
- 检查每个 class.
中使用的注释
JUnit 测试的最新版本class有@Test 注释。所以如果你得到 @org.junit.Test
注释,你可以说它是一个测试 class.
Method[] methods = classObject.getClass().getMethods();
for (Method method : methods) {
Annotation[] annotations = method.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation.toString());
}
}
此代码的输出 -
@org.junit.Test(expected=class org.junit.Test$None, timeout=0)
@org.junit.After()
- 找到测试 class 后执行它。
我需要一个解决方案来从 jar 文件中识别测试 classes 并执行它们。那是我的 Web 应用程序接受一个 jar 文件作为输入并识别 jar 中的测试 classes 和执行它们并显示结果。
目前,每当我尝试从 jar.I 访问 class 文件时,我都遇到 class 未找到异常,认为我需要将外部 jar 文件添加到我的 class 路径?
以下是您可以遵循的一些步骤:
- 获取 Jar 文件路径
- 从中读取 classes
- 遍历那些 classes
- 获取每个 class 的方法
- 检查每个 class. 中使用的注释
JUnit 测试的最新版本class有@Test 注释。所以如果你得到
@org.junit.Test
注释,你可以说它是一个测试 class.Method[] methods = classObject.getClass().getMethods(); for (Method method : methods) { Annotation[] annotations = method.getAnnotations(); for (Annotation annotation : annotations) { System.out.println(annotation.toString()); } }
此代码的输出 -
@org.junit.Test(expected=class org.junit.Test$None, timeout=0)
@org.junit.After()
- 找到测试 class 后执行它。