gpt4 book ai didi

Java自定义Annotation聚合多个注解

转载 作者:IT老高 更新时间:2023-10-28 13:55:04 32 4
gpt4 key购买 nike

我正在为我的 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 类

只使用了一个注解
@ControllerTest
public class XXControllerTest {
}

修改后测试失败

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

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

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

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

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

最佳答案

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

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

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

关于Java自定义Annotation聚合多个注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33345605/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com