Java JUnit: programmatically setup a test retry mechanism
In a Java CI pipeline, sometimes it is useful to retry tests, to handle false positive errors (such as network errors).
To do so, we can use the org.junit-pioneer
library. Also, we want to be able to change the number of retry attempts programmatically,
and disable the retry mechanism when the tests are run from an IDE like IntelliJ.
First let’s add the lib-custom
, junit
and junit-pioneer
dependencies to our pom.xml
:
Then, let’s create a class that wil extend io.github.jleblanc64.libcustom.custom.test.TestRetryDefault
,
and will load some custom code that dynamically passes our parameters to junit-pioneer
:
Now, we can extend all of our existing test classes with this new TestRetry
class.
All test methods that have the annotation org.junit.jupiter.api.Test
will be retried on failure, using the parameters from above.
For instance, the following test will be retried 4 times (if not run from IntelliJ):
You can see the full working code in my Github repo. You can ask a question in the issues if you need.