How to Merge Multiple Annotations in JAVA

Hello all, in this article I will demonstrate you how to use a common custom annotation to merge the other annotations in JAVA. If you need to use multiple annotations in your test classes, you can use this technique to merge some annotations. In this way, whenever you need to add or change some annotation for your test classes, you can easy to modify it in your base annotation.

In order to do this, you need to create a custom annotation class. Let’s name it BaseTestAnnotation and lets add @RepeatedIfExceptionsTest(repeats = 3) annotation in this class. In this way, we can make this annotation as global to all of our test classes.

package annotations;

import io.github.artsok.RepeatedIfExceptionsTest;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@RepeatedIfExceptionsTest(repeats = 3)
public @interface BaseTestAnnotation {
}

After that, we can use BaseTestAnnotation class instead of @Test annotation as shown below.

and when we run our test, we will see that our tests will repeat 3 times when they fail.

If you want to change retry count in your tests, you can just change the retry count in BaseTestAnnotation file. If you don’t use this technique and if you put @RepeatedIfExceptionsTest(repeats = 3) annotation on top of your all test methods, then you need to change the repeat count for each test method. It will be a cumbersome process for us. But with common base test annotation, it will be so easy to change repeat count for all test methods.

Note: New JUnit 5 parallel execution feature is not compatible with Repeat feature. If you try to run your tests in parallel, they will run in parallel but they won’t rerun when they will fail. You can see this on below screenshot. Here is the comprehensive JUnit 5 Repeat Test article.

Thanks.
Onur Baskirt

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.