【问题标题】:Java custom Annotation aggregate multiple annotationsJava自定义Annotation聚合多个注解
【发布时间】:2016-01-25 13:03:13
【问题描述】:

我正在为我的RestControllers写一个TestCases
对于每个ControllerTest calss,我使用以下注释

@WebAppConfiguration
@RunWith(value = SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebConfig.class, TestAppConfig.class})

所以,我决定定义自己的注释,包含所有这样的注释

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@WebAppConfiguration
@RunWith(value = SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebConfig.class, TestAppConfig.class})
public @interface ControllerTest {
}

然后,我只为我所有的ControllerTest classes 使用了一个注释

@ControllerTest
public class XXControllerTest {
}

修改后测试失败

java.lang.IllegalArgumentException: WebApplicationContext is required
    at org.springframework.util.Assert.notNull(Assert.java:115)

为了让它再次工作,我需要将@RunWith(SpringJUnit4ClassRunner.class) 添加到Test class

@ControllerTest
@RunWith(SpringJUnit4ClassRunner.class)
public class XXControllerTest {
}

我的问题是为什么我的 @ControllerTest 注释在包含 @RunWith(SpringJUnit4ClassRunner.class) 注释时不起作用? @RunWith 注释有什么特别之处吗?还是我错过了什么?

PS:我对Spring config classes 使用相同的方法,它们工作得很好。

【问题讨论】:

    标签: java spring unit-testing annotations


    【解决方案1】:

    这种机制,您可以拥有“元注释”,这些“元注释”本身用其他注释进行注释,然后应用于您放置元注释的类,这是 Spring 框架特有的。它不是 Java 注释的标准特性。

    它不起作用,因为 JUnit 不理解这种机制。 @RunWith 注释是一个 JUnit 注释。 JUnit 不明白它应该查看您的 @ControllerTest 元注释上的注释。

    因此,这种机制适用于 Spring 处理的注解,但不适用于 JUnit 等其他工具处理的注解。

    【讨论】:

      【解决方案2】:

      用spring注解创建meta-annotations是一个spring特性,@RunWith是一个JUnit注解。

      【讨论】:

        猜你喜欢
        • 2014-01-13
        • 1970-01-01
        • 1970-01-01
        • 2015-01-08
        • 1970-01-01
        • 2011-06-12
        • 2018-10-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多