java - JUnit4 根据自定义 java 注释跳过测试

标签 java junit annotations

我希望我的 JUnit4 测试根据我用 Java 创建的自定义注释执行。此自定义注释的目的是让 JUnit4 注意到只有当机器的平台与注释中指定的平台相匹配时才应运行测试。

假设我有以下注释:

public @interface Annotations {
    String OS();
    ...
}

以及以下测试:

public class myTests{

    @BeforeClass
    public setUp() { ... }

    @Annotations(OS="mac")
    @Test
    public myTest1() { ... }

    @Annotations(OS="windows")
    @Test
    public myTest2() { ... }

    @Annotation(OS="unix")
    @Test
    public myTest3() { ... }

}

如果我要在 Mac 机器上执行这些测试,那么只有 myTest1() 应该被执行,其余的应该被忽略。但是,我目前对如何实现这一点感到困惑。我如何让 JUnit 读取我的自定义注释并检查是否应该运行测试。

最佳答案

您可以使用类别,也可以实现您自己的自定义 JUnit 运行程序。扩展默认的 JUnit 运行器非常简单,并且允许您定义要以任何您可能想要的方式运行的测试列表。这包括只查找那些带有特定注释的测试方法。我在下面包含代码示例,您可以将它们用作您自己实现的基础:

注释:

@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnnotation {
   String OS();
}

自定义亚军类:

public class MyCustomTestRunner extends BlockJUnit4ClassRunner {

   public MyCustomTestRunner(final Class<?> klass) throws InitializationError {
      super(klass);
   }

   @Override
   protected List<FrameworkMethod> computeTestMethods() {
      // First, get the base list of tests
      final List<FrameworkMethod> allMethods = getTestClass()
            .getAnnotatedMethods(Test.class);
      if (allMethods == null || allMethods.size() == 0)
         return allMethods;

      // Filter the list down
      final List<FrameworkMethod> filteredMethods = new ArrayList<FrameworkMethod>(
            allMethods.size());
      for (final FrameworkMethod method : allMethods) {
         final MyCustomAnnotation customAnnotation = method
               .getAnnotation(MyCustomAnnotation.class);
         if (customAnnotation != null) {
            // Add to accepted test methods, if matching criteria met
            // For example `if(currentOs.equals(customAnnotation.OS()))`
            filteredMethods.add(method);
         } else {
            // If test method doesnt have the custom annotation, either add it to
            // the accepted methods, or not, depending on what the 'default' behavior
            // should be
            filteredMethods.add(method);
         }
      }

      return filteredMethods;
   }
}

示例测试类:

@RunWith(MyCustomTestRunner.class)
public class MyCustomTest {
   public MyCustomTest() {
      super();
   }

   @Test
   @MyCustomAnnotation(OS = "Mac")
   public void testCustomViaAnnotation() {
      return;
   }
}

关于java - JUnit4 根据自定义 java 注释跳过测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13590557/

相关文章:

java - 如何进行桌面 Java 应用程序的自动化验收测试?

java - SpringRunner/JUnit 运行/测试私有(private)(非测试)方法

java - 如何按天比较DateTime?

ios - 忽略 map 查看 :didSelectAnnotationView when long press is occuring

java - hibernate 映射帮助!

Java项目恢复

java - 如何编写一个记录参数和返回值的拦截器?

java - _version、_id 等的 spring-data-elasticsearch 元数据注释

java - 停止观看 android - 暂停,然后开始并从它停止的地方开始

java - 在 json 模式中使用正则表达式来验证没有空格的字符串?