How to Write Custom Annotations as Meta Annotations in JUnit
Write composed annotations in JUnit 5 with meta annotations: combine tags, extensions and display names into reusable test annotations for cleaner test code.

When a dozen test classes carry the same stack of annotations, the stack should have a name. A class that starts with @SpringBootTest(webEnvironment = RANDOM_PORT), @ActiveProfiles("test"), @Tag("integration") and a timeout is saying the same thing every time, and each copy is a chance to forget one line. JUnit 5 solves this with meta-annotations: annotations you can place on your own annotation type, which then stands in for the whole group. This post builds five of them and covers the rules that decide whether JUnit sees them. It targets JUnit 5.13 on Java 25.
The basic idea
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Tag("slow")
@Timeout(value = 30, unit = TimeUnit.SECONDS)
public @interface SlowTest {
}class ReportGeneratorTest {
@Test
@SlowTest
void generatesLargeReport() {
// ...
}
}@SlowTest now means "tagged slow, with a 30 second timeout". JUnit walks the annotations on a test, and for any it does not recognize it looks at the annotations on that annotation. Whatever it finds is treated as if you had written it on the test itself. The mechanism is the same one the JDK uses for @Inherited lookups, applied by JUnit's own annotation support utilities.
Two attributes decide whether it works. @Retention(RUNTIME) is required, because a source-retention annotation is gone before the tests run, and the failure is silent: the test runs without the tag and without the timeout, and nothing complains. @Target limits where the annotation can be used, so set it to what you mean. A tag and timeout make sense on a class or a method, which is what the example allows.
Folding in @Test itself
A composed annotation can include @Test, so one line both marks a method as a test and classifies it:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Test
@Tag("smoke")
public @interface SmokeTest {
}@SmokeTest
void servicePingsOk() {
assertEquals("ok", client.ping());
}This works because @Test is itself meta-present, and the same trick applies to @ParameterizedTest and @RepeatedTest. A caution before you use it everywhere: a method carrying both @Test and a composed annotation that already includes @Test is registered twice, and JUnit fails with a message about a method annotated more than once. One of the two must go.
Bundling extensions
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@ExtendWith({MockitoExtension.class, TimingExtension.class})
@Tag("unit")
public @interface UnitTest {
}@UnitTest
class PriceCalculatorTest {
@Mock
Catalog catalog;
@Test
void appliesVolumeDiscount() {
when(catalog.basePrice("A-1")).thenReturn(new BigDecimal("10.00"));
// ...
}
}One annotation registers both extensions and tags the class. Extension order follows declaration order, so list the one that must run first at the start. How extensions hook into the lifecycle is explained in the extension model.
Spring tests are the strongest case
Spring Boot tests accumulate configuration quickly. Naming the common set once pays off more here than anywhere else:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
@Tag("integration")
public @interface IntegrationTest {
}There is a performance reason beyond tidiness. Spring caches an application context by its configuration, so two classes with identical annotations share one context, and every difference, even a different profile order, builds another. Starting a context for each of forty classes can dominate a build. A single @IntegrationTest makes the identical configuration the default, and the cost of a variation becomes visible in review. The caching rules are in caching the test context.
Conditions as names
Conditions compose too:
@Retention(RetentionPolicy.RUNTIME)
@EnabledIfEnvironmentVariable(named = "CI", matches = "true")
@Tag("ci-only")
public @interface CiOnly {
}A test marked @CiOnly is skipped on a laptop and runs on the build server. That is better than a comment saying "only run in CI", because a skipped test shows up in reports as skipped and not as absent.
What does not compose
A few annotations take values that a meta-annotation cannot vary. @DisplayName("...") has a fixed string, so putting it on a composed annotation gives every use the same name, which is never what you want. Use naming conventions for display names, as described in display names.
The same limit applies to attributes in general. If @SlowTest fixes the timeout at 30 seconds, no test can ask for 60 through that annotation. Spring solves this with @AliasFor, which forwards an attribute of the composed annotation to one of the meta-annotation, but it is a Spring feature and plain JUnit has no equivalent. When you need a different timeout, create a second annotation, or write @Timeout directly on the test, which wins over the meta-annotation on the same element.
Stacking and conflicts
Composed annotations stack, and their effects add up. A test with @UnitTest and @SlowTest has two tags, and the timeout applies. Two annotations that set the same single-valued thing, such as two different @Timeout values, conflict, and JUnit uses the one it finds first in its search order, which is not a rule worth memorizing. Avoid the situation: keep each composed annotation to one concern, and do not stack two that set the same attribute.
How to check that it worked
A composed annotation that JUnit ignores fails silently, so verify the first use. Run the build with the tag filter that should select the test and confirm the test appears in the report, then exclude the tag and confirm it disappears. For a timeout, write one throwaway test that sleeps past the limit and make sure it fails. Doing this once per new annotation takes a minute and catches a missing @Retention before forty classes depend on it.
Naming discipline
Pick a short list and document it where tests are written: @UnitTest, @IntegrationTest, @SlowTest, maybe @CiOnly. Four annotations cover most codebases. A team that grows twenty of them has traded one kind of noise for another, because a reader now has to look up what each includes. A good test of a composed annotation is whether its name predicts its contents. If someone must open the declaration to find out, rename it or delete it.
The tags pay off in the build. Surefire and Gradle can include or exclude by tag, so a quick local run skips integration and the pipeline runs everything. The filtering syntax is covered in JUnit tags and Gradle JUnit setup.
Verify that your annotation does what it says
A composed annotation is a promise about what is applied, and nothing checks it unless you do. JUnit's own AnnotationSupport reads meta-annotations the way the engine does, so a test can assert that the stack is complete:
class AnnotationContractTest {
@Test
void integrationTestIsTaggedAndExtended() {
assertTrue(AnnotationSupport.isAnnotated(SampleIntegrationTest.class, Tag.class));
List<ExtendWith> extensions = AnnotationSupport.findRepeatableAnnotations(
SampleIntegrationTest.class, ExtendWith.class);
assertTrue(extensions.stream()
.flatMap(e -> Arrays.stream(e.value()))
.anyMatch(type -> type == ContainersExtension.class));
}
@IntegrationTest
static class SampleIntegrationTest {
@Test void runs() {}
}
}The sample class carries your composed annotation, and the assertions read what JUnit will see. When someone removes the @Tag from the annotation to "simplify" it, every integration test silently joins the fast stage, and this test fails first. A second, cheaper check is to list the tests that ran with a tag in the build report after a change to the annotation, and compare the count with the previous build.
Where a wrapper is not worth it
A group of annotations used in one class needs no wrapper. Create the composed annotation when the same group appears three or more times, or when the group expresses a category the team talks about. The reference is the JUnit 5 user guide on meta-annotations, and the Jupiter API lists which annotations are allowed on which element.


