gpt4 book ai didi

java - 如何将 JUnit 注解码合成自定义注解?

转载 作者:行者123 更新时间:2023-12-01 19:29:09 24 4
gpt4 key购买 nike

(使用 OpenJDK-13 和 JUnit5-Jupiter)

问题是我的每个单元测试都使用了一个不小的 JUnit 注释系统,如下所示:

@ParameterizedTest
@MethodSource("myorg.ccrtest.testlogic.DataProviders#standardDataProvider")
@Tags({@Tag("ccr"), @Tag("standard")})

这使得测试编写有点乏味,测试代码有点长,当然,当需要更改时,这是一件苦差事!

想知道我是否可以创建自己的 JUnit 注释:@CcrStandardTest,这将暗示上述所有注释?

我还尝试在类定义中向上移动注释(希望它们随后适用于类的所有方法),但编译器说不:“@ParameterizedTest 不适用于类型”

最佳答案

你可以做一个composed annotation :

JUnit Jupiter annotations can be used as meta-annotations. That means that you can define your own composed annotation that will automatically inherit the semantics of its meta-annotations.

例如:

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD})
@ParameterizedTest
@MethodSource("myorg.ccrtest.testlogic.DataProviders#standardDataProvider")
@Tag("ccr")
@Tag("standard")
public @interface CcrStandardTest {}

然后,您可以将组合注释放在您的测试方法上:

@CcrStandardTest
void testFoo(/* necessary parameters */) {
// perform test
}

关于java - 如何将 JUnit 注解码合成自定义注解?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60324735/

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