How to combine JUnit annotations into a custom annotation?

我怕爱的太早我们不能终老 提交于 2020-03-05 04:58:07

问题


(Using OpenJDK-13 and JUnit5-Jupiter)

The problem is that my unit tests each make use of a not-small JUnit annotation system, something like this:

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

This makes test authoring a little tedious, test code a little long and of course, when a change is needed, it's a chore!

Was wondering if I could create my own JUnit annotation: @CcrStandardTest, which would imply all of the annotations above?

I also tried shifting the annotations up in the class definition (hoping they would then apply to all methods of the class), but the compiler says no: "@ParameterizedTest is not applicable to type"


回答1:


You can make a 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.

For example:

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 {}

You would then place the composed annotation on your test method:

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


来源:https://stackoverflow.com/questions/60324735/how-to-combine-junit-annotations-into-a-custom-annotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!