我已经创建了一些自定义注释,用于通过JUnit运行的系统测试。
一个测试看起来像这样:
@TestCaseName("Change History")
public class ChangeHistory extends SystemTestBase
{
@Test
@Risk(1)
public void test()
{
...
我现在正在实现一个Test Runner,它将报告测试名称、风险和用于文档目的的位置。
public class MyRunner extends BlockJUnit4ClassRunner
{
...
@Override
protected void runChild(final FrameworkMethod method, RunNotifier notifier)
{
...
System.out.println("Class annotations:");
Annotation[] classanno = klass.getAnnotations();
for (Annotation annotation : classanno) {
System.out.println(annotation.annotationType());
}
System.out.println("Method annotations:");
Annotation[] methanno = method.getAnnotations();
for (Annotation annotation : methanno) {
System.out.println(annotation.annotationType());
}
输出为
Class annotations:
Method annotations:
interface org.junit.Test
所以getAnnotations()
似乎只返回JUnit的注释,而不是所有的注释。这在JUnit的文档中没有提到:
返回该方法的注释
返回类型是java.lang.Annotation
,这让我相信我可以使用任何注释。我像下面这样定义注释—我只是使用它,当出现错误时,我让Eclipse生成注释:
public @interface Risk {
int value();
}
我如何获得测试类和测试方法的所有注释?
需要设置"Risk
"注释的保留策略为"RUNTIME
"。否则,该注释将在编译后被丢弃,并且在代码执行期间不可用。
这应该是工作的:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Risk {
int value();
}