Repeating a test case in Junit

09:00

Many times we need to create Junit tests which needs to be repeated over and over (may be with different data set). Many of us did this by writing custom Runner or sometimes using parameterized test.

Junit4 comes with @Rule, which can be used for repeating a testcase. Actually, rules are used to add additional functionality which applies to all tests within a test class, but in a more generic way. Using @Rule for such a requirement is preferable because it does things in a more clean way. Moreover by using @Rule we still has option to use pretty useful runners like @RunWith(PowerMockRunner.class) etc.

Let’s create a simple Rule to repeat a test case to ‘N’ number of times:
package blog.techypages.rule;

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

/**
 * Rule class to be repeat the same test case over and over.
 * 
 * @author abhishek
 *
 */
public class RepeatRule implements TestRule {
    private int count;
    
    public RepeatRule(int count) {
        this.count = count;
    }
    
    @Override
    public Statement apply(final Statement base, Description description) {
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                for (int i = 0; i < count; i++) {
                    base.evaluate();
                }
            }
        };
    }

}


Let’s make a quick testcase and see how it works:
package blog.techypages.rule;

import org.junit.Rule;
import org.junit.Test;

/**
 * Class to demonstrate @see RepeatRule usage.
 * 
 * @author abhishek
 *
 */
public class RepeatTest {
    @Rule
    public RepeatRule rule = new RepeatRule(10);
    private int counter = 0;

    @Test
    public void test() {
        System.out.println(counter++);
    }

}


Output:
0
1
2
3
4
5
6
7
8
9


It’s really easy and useful feature of Junit. Use it next time and you will find it a great help.

Hope this article helped. Happy learning... :)

You Might Also Like

3 comments