JUnit 测试中的注释数量不正确

Number of annotations at JUnit test incorrect

我创建了一些自定义注解用于通过 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() 似乎只 return JUnit 注释而不是所有注释。这个没有提到in the documentation of JUnit:

Returns the annotations on this method

return 类型是 java.lang.Annotation 这让我相信我可以使用任何注解。我定义了如下注释 - 我只是使用它,当出现错误时,我让 Eclipse 生成注释:

public @interface Risk {
    int value();
}

如何获取测试class和测试方法的所有注释?

您需要将 Risk 注释的保留策略设置为 RUNTIME。否则注解会在编译后被丢弃,在代码执行过程中不可用。

这应该有效:

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface Risk {
  int value();
}