Java自定义注解聚合多个注解

23

我正在为我的RestControllers编写TestCases


对于每个ControllerTest类,我使用以下注释

@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类只使用了一个注解。

@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注解有什么特殊之处吗?还是我漏了什么东西?

附注:我对Spring配置类使用相同的方法,它们可以正常工作。

2个回答

19

这种机制可以使用“元注解”来注释其他注解,然后应用于放置了该元注解的类,这是Spring框架特有的功能。它不是Java注解的标准特性。

由于JUnit不理解这种机制,所以它不起作用。 @RunWith 注解是JUnit注解,JUnit并不知道它应该查看放置在 @ControllerTest 元注解中的注解。

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


这对我的情况适用吗?https://stackoverflow.com/questions/77229486/how-to-pass-argument-of-meta-annotation-to-inner-annotaion - undefined

3

将Spring注释创建为元注释是Spring的一项功能,而@RunWith是JUnit注释。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接