In JUnit 5, they came up with an annotation that does just that – run a test method n
times. Introducing
@RepeatedTest(int value). You may read more about it in JUnit 5 User Guide.
[wp_ad_camp_5]
However, we will demonstrates how to perform repeated tests in JUnit 4 for this post. It involves creating a class that implements the TestRule interface, another class that implements Statement interface and a new annotation.
The Annotation class
This annotation will be used along side the @Test annotation.
1 2 3 4 5 6 7 8 9 10 11 12 | package com.turreta.junit4.repeatedtest.util; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ java.lang.annotation.ElementType.METHOD }) public @interface RepeatTest { int times(); } |
RepeatableTestStatement class
[wp_ad_camp_4]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | package com.turreta.junit4.repeatedtest.util; import org.junit.runners.model.Statement; public class RepeatableTestStatement extends Statement { private final int times; private final Statement statement; private RepeatableTestStatement(int times, Statement statement) { this.times = times; this.statement = statement; } @Override public void evaluate() throws Throwable { for(int i = 0; i < times; i++) { statement.evaluate(); } } } |
RepeatedTestRule class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | package com.turreta.junit4.repeatedtest.util; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; public class RepeatedTestRule implements TestRule { @Override public Statement apply(Statement statement, Description description) { Statement result = statement; RepeatTest repeat = description.getAnnotation(RepeatTest.class); if(repeat != null) { int times = repeat.times(); result = new RepeatableTestStatement(times, statement); } return result; } } |
Put it all together
[wp_ad_camp_3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | package com.turreta.junit4.repeatedtest; import com.turreta.junit4.repeatedtest.util.RepeatTest; import com.turreta.junit4.repeatedtest.util.RepeatedTestRule; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class ComTurretaJunit4RepeatedtestApplicationTests { @Rule public RepeatedTestRule repeatRule = new RepeatedTestRule(); @Test @RepeatTest(times = 7) public void repeatedTestExample() { System.out.println("Test example"); } } |
This outputs:
[wp_ad_camp_2]
Download the codes
https://github.com/Turreta/JUnit-4-Run-Test-Method-More-than-Once
References
[wp_ad_camp_1]