问题
(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