【问题标题】:Custom Annotations for Spring Boot TestsSpring Boot 测试的自定义注解
【发布时间】:2022-01-04 01:56:23
【问题描述】:

是否可以覆盖自定义注解中使用的注解的参数值?

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@SpringBootTest(classes = [HOW_TO_CHANGE_THESE])
@ComponentScan(basePackages = {[HOW_TO_CHANGE_THESE]})
@ActiveProfiles("testing")
public @interface IntegrationTest {
}

我的目的是减少我的测试中的注释数量,同时为所有这种类型的测试设置默认值。我想这样使用它:

@IntegrationTest(classes="...", basePackages="...")
class AbcTest {
}

提前致谢!

【问题讨论】:

    标签: java spring spring-boot unit-testing


    【解决方案1】:

    是的,如果您使用的是 Spring 框架,这是可能的。为此,它有一个特殊的@AliasFor 注释:

    @AliasFor 是一个注解,用于为注解属性声明别名。

    您可以在官方文档herethis tutorial 中找到更多使用示例。

    另外,在官方文档here中有关于如何在Spring Test Context中使用元注解的细节。

    您使用此注释的示例将如下所示:

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE)
    @SpringBootTest
    @ComponentScan
    @ActiveProfiles("testing")
    public @interface IntegrationTest {
    
        @AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
        String[] basePackages() default {};
    
        @AliasFor(annotation = SpringBootTest.class, attribute = "classes")
        Class<?>[] classes() default {};
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-04
      • 1970-01-01
      • 1970-01-01
      • 2017-06-21
      • 1970-01-01
      • 2019-03-15
      • 2020-11-04
      • 2020-05-20
      相关资源
      最近更新 更多