问题描述
我正在为我的 RestControllers
编写一个 TestCases
对于每个 ControllerTest calss
我使用以下注释
Im writing a TestCases
for my RestControllers
For each ControllerTest calss
I use the following annotations
@WebAppConfiguration
@RunWith(value = SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebConfig.class, TestAppConfig.class})
所以,我决定定义我自己的注释女巫,包含所有这样的注释
So, I decided to define my own annotation witch contain all those annotations like this
@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
And to make it work again it required me to add the @RunWith(SpringJUnit4ClassRunner.class)
to the Test class
@ControllerTest
@RunWith(SpringJUnit4ClassRunner.class)
public class XXControllerTest {
}
我的问题是为什么我的 @ControllerTest
注释在包含 @RunWith(SpringJUnit4ClassRunner.class)
注释时不起作用?@RunWith
注释有什么特别之处吗?还是我错过了什么?
My question is why my @ControllerTest
annotation doesn't work while its contain the @RunWith(SpringJUnit4ClassRunner.class)
annotation? is there anything special about the @RunWith
annotation? or did I miss something?
PS:我对 Spring 配置类
使用相同的方法,它们工作得很好.
PS: I use the same approach for Spring config classes
and they work just fine.
推荐答案
这种机制,您可以拥有元注释",这些注释本身与其他注释一起注释,然后应用于您放置元注释的类注解,是特定于 Spring 框架的东西.它不是 Java 注释的标准特性.
This mechanism, where you can have "meta-annotations" that are themselves annotated with other annotations, which then apply to the class on which you put your meta-annotation, is something that is specific to the Spring Framework. It is not a standard feature of Java annotations.
它不起作用,因为 JUnit 不了解这种机制.@RunWith
注释是一个 JUnit 注释.JUnit 不明白它应该查看 @ControllerTest
元注释上的注释.
It doesn't work because JUnit does not understand this mechanism. The @RunWith
annotation is a JUnit annotation. JUnit does not understand that it should look at the annotations that are on your @ControllerTest
meta-annotation.
因此,此机制适用于由 Spring 处理的注释,但不适用于由其他工具(如 JUnit)处理的注释.
So, this mechanism works with annotations that are processed by Spring, but not with annotations that are processed by other tools such as JUnit.
这篇关于Java自定义注解聚合多个注解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!