1

(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"

DraxDomax
  • 1,008
  • 1
  • 9
  • 28

1 Answers1

5

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
}
Slaw
  • 37,820
  • 8
  • 53
  • 80
  • Thank you, this is what I was looking for. However, I am not out of the woods yet :( When I created my meta-tag and used it in a prototype test method, JUnit execution says: "no tests were found". When I added (a)Test directly to the test method, it "found" the test (and executed), but IDE suggests "suspicious combination (a)Test and parameterized source". I know (a)Parameterized test implies (a)Test - but why JUnit doesn't consider (a)CcrStandardTest as a (a)Test? – DraxDomax Feb 21 '20 at 12:36
  • OK, upon further analysis, it's because I didn't apply (a)Retention and (a)Target, which you suggested... Tests are running now but I wish JUnit documentation explained (a)Target and (a)Retention! Could you please elaborate with a few words? :) Created new question: https://stackoverflow.com/questions/60339277 – DraxDomax Feb 21 '20 at 13:16
  • 1
    I added imports to this answer to hopefully make things more clear. I'll explain more about `@Retention` and `@Target` in your other Q&A. – Slaw Feb 21 '20 at 13:51