【问题标题】:How to make sure the @Scheduled annotation is present on the method如何确保方法上存在@Scheduled 注释
【发布时间】:2019-05-22 07:16:13
【问题描述】:

在我们的Spring Boot 应用程序中,我们有一个带有@Scheduled 注释的方法:

@Scheduled(fixedRate = 1000L * 60 * 10, initialDelay = 1000L * 60 * 5)
   public void doSomethingFromTimeToTime(){....}

在我们的 Maven 构建测试阶段,我们希望确保:

  1. 存在注释(例如,开发人员没有错误地删除)并且
  2. 包含这些精确值

有没有办法在单元/集成测试中以某种方式对其进行测试?还是在构建阶段的另一种意思?

我们不需要测试 Spring 的 Scheduler 本身,只需确保注解存在即可。

【问题讨论】:

  • 嗨@riorio,你会找Class#getAnnotation()吗?拥有Annotation 对象后,您可以使用提供的 getter 检查其上的各个属性。
  • @PaulBenn 这正是我所需要的。您想为荣誉添加答案吗?
  • 很高兴我能帮上忙。一秒钟,我将其添加为答案,以便其他人也可以受益。

标签: java unit-testing spring-boot integration-testing scheduler


【解决方案1】:

您可以使用Class.getAnnotation(Class<A> annotationType) 方法测试Class 对象上是否存在注释,其中A 是泛型类型参数,就像T 通常是一样。

示例用法:

Scheduled scheduledAnnotation = MySpringScheduler.class.getAnnotation(Scheduled.class).

获得注解后,您可以使用注解提供的方法访问字段,就像在普通类上一样:

scheduledAnnotation.fixedDelay();

【讨论】:

    【解决方案2】:

    我想这样你可以很容易地使用反射得到它

    Class<?> cls = Class.forName(name);
    
        cls.getDeclaredAnnotations(); // get all annotation
        (cls.getDeclaredMethods()[0]).getAnnotations(); //get annotation of a method
        Annotation ety = cls.getAnnotation(Annotation.class); // get annotation of particular annotation class
    

    参考How to get the value of annotation using Reflection in Java

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 2020-10-02
      • 2015-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多