7

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?

awfun
  • 2,316
  • 4
  • 31
  • 52
  • Besides the given answer, you might also want to look at this: https://github.com/EaseTech/easytest-core – SiKing May 01 '16 at 17:11

1 Answers1

6
  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.

Nico
  • 1,554
  • 1
  • 23
  • 35
Akah
  • 1,890
  • 20
  • 28
  • Is there a way to run these tests under different names? I mean, in Jenkins I need to observe runs of these classes as: MyTest.doTest[paramsFor1stRun], MyTest.doTest[paramsFor2ndRun] – awfun Apr 28 '16 at 09:08
  • Does this thread answers to your question ? http://stackoverflow.com/questions/650894/changing-names-of-parameterized-tests. It seems to be existing since JUnit 4.11. – Akah Apr 28 '16 at 09:13
  • Thank you, I decided to create my own test runner, but Parametrized runner helped me a lot to understand. Probably I will use it in the future to manage my tests – awfun Apr 29 '16 at 13:41
  • It is another nice proof that JUnit is not a framework for the real life. Simple initiation of two arrays and calling them in cycle is more short and convenient than the way the post proposes. And by arrays you can do it for any test function, not creating separate test class for it. Or use TestNG. Of course, my comment is not against the post - +1 - I respect people that can make work well even JUnit. (personally, I always wrote different runner) – Gangnus Sep 20 '17 at 09:10