![](/img/trans.png)
[英]How to create and use a Custom Annotation having Spring+JUnit Test Config annotations?
[英]How to combine JUnit annotations into a custom annotation?
(使用 OpenJDK-13 和 JUnit5-Jupiter)
問題是我的單元測試每個都使用了一個不小的 JUnit 注釋系統,如下所示:
@ParameterizedTest
@MethodSource("myorg.ccrtest.testlogic.DataProviders#standardDataProvider")
@Tags({@Tag("ccr"), @Tag("standard")})
這使得測試編寫有點乏味,測試代碼有點長,當然,當需要更改時,這是一件苦差事!
想知道我是否可以創建自己的 JUnit 注釋: @CcrStandardTest
,這意味着上面的所有注釋?
我還嘗試將類定義中的注釋向上移動(希望它們隨后適用於類的所有方法),但編譯器說不:“@ParameterizedTest 不適用於類型”
您可以進行組合注釋:
JUnit Jupiter 注釋可以用作元注釋。 這意味着您可以定義自己的組合注釋,該注釋將自動繼承其元注釋的語義。
例如:
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.