Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 549
awfun Avatar asked Aug 04 '26 07:08

awfun


1 Answers

  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.

like image 106
Akah Avatar answered Aug 05 '26 23:08

Akah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!