Search code examples
javaunit-testingjunit4

Make jUnit runner run test class multiple times with different parameters


I have some jUnit4 test classes, which I want to run multiple times with different parameters passed in annotation. For example, like this:

@RunWith(MyClassRunner.class)
@Params("paramFor1stRun", "paramFor2ndRun")
class MyTest {
  @Test
  public void doTest() {..}
}

I assume Runner can help me with it, but I don't know how to implement this. Could you advice please?


Solution

    1. You need to add the annotation @RunWith(Parameterized.class) to your test.

    2. Then, create a constructor for you class with the parameters you need:

      public Test(String pParam1, String param2) {
          this.param1 = pParam1;
          this.param2 = pParam2;
      }
      
    3. Then, declare a method like this (Which provides an array of parameters corresponding to the constructor):

      @Parameters
      public static Collection<Object[]> data() {
        Object[][] data = {{"p11", "p12"}, {"p21", "p22"}};
        return Arrays.asList(data);
      }
      
    4. You can do you test, which will be executing for each row of your array:

      @Test
      public void myTest() {  
          assertEquals(this.param1,this.param2);
      }
      

    You've got a faster way without defining the constructor, if you use the annotation @Parameter(value = N) where N is the index of you parameter array.