junit implementation of multiple runners

3.1k views Asked by At

I have been trying to create a personalized test suite by creating a suiterunner which extends runner. In the test suite which is annotated with @RunWith(suiterunner.class) i am referring to the test classes which need to be executed.

Within the test class i need to repeat a particular test, for doing so i am using the solution as mentioned here : http://codehowtos.blogspot.com/2011/04/run-junit-test-repeatedly.html . but since i have created a suiterunner which triggers the test class and within that test class i am implementing @RunWith(ExtendedRunner.class), an initialization error is thrown.

I need help to manage these 2 runners and also is there any way to combine 2 runners for a particular test? Is there any other way to solve this issue or any easier way to go ahead?

1

There are 1 answers

0
Nitin Tripathi On

In case you are using the latest JUnit you might @Rules to be a lot cleaner solution to your problem. Here is a sample;

Imagine this is your application;

package org.zero.samples.junit;

/**
 * Hello world!
 * 
 */
public class App {
  public static void main(String[] args) {
    System.out.println(new App().getMessage());
  }

  String getMessage() {
    return "Hello, world!";
  }
}

This is your test class;

package org.zero.samples.junit;

import static org.junit.Assert.*;

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

/**
 * Unit test for simple App.
 */
public class AppTest {

  @Rule
  public RepeatRule repeatRule = new RepeatRule(3); // Note Rule

  @Test
  public void testMessage() {
    assertEquals("Hello, world!", new App().getMessage());
  }
}

Create a rule class like;

package org.zero.samples.junit;

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

public class RepeatRule implements TestRule {

  private int repeatFor;

  public RepeatRule(int repeatFor) {
    this.repeatFor = repeatFor;
  }

  public Statement apply(final Statement base, Description description) {
    return new Statement() {

      @Override
      public void evaluate() throws Throwable {
        for (int i = 0; i < repeatFor; i++) {
          base.evaluate();
        }
      }
    };
  }

}

Execute your test case as usual, just that this time your test cases will be repeated for the given number of times. You might find interesting use cases where in @Rule might really prove to be handy. Try creating composite rules, play around you surely will be glued..

Hope that helps.