3

Is it possible to run parameterized test for each method of test class with JUnitParams and class level annotations? Something like:

@RunWith(JUnitParamsRunner.class)
@Parameters(method = "paramsGenerator")
public class TestMethod {

    public Integer[] paramsGenerator() {
        return new Integer[] {1, 2, 3};
    }

    @Test
    public void test1(Integer myInt) {
        ......
    }

    @Test
    public void test2(Integer myInt) {
        ......
    }
}
Feedforward
  • 4,521
  • 4
  • 22
  • 34
  • 2
    Did you try before asking? This should be de default behaviour. – BetaRide May 15 '17 at 07:42
  • Yes, it should be, but it's not. I'm getting `Method test1 should have no parameters` – Feedforward May 15 '17 at 07:57
  • 1
    You have to define a constructor that takes the param and stores it in a field. the methods can then use the value from the field - not as param. – Andy May 15 '17 at 07:58

2 Answers2

4

No, you cannot have a class-level parameters annotation that would cover all test methods. You must declare @Parameters(method = "paramsGenerator") on each test method. Your use case is pretty rare - most often different test methods require different parameters (eg. you have one method for valid and one for invalid input).

Adam Michalik
  • 9,678
  • 13
  • 71
  • 102
1

The test class should be like this:

@RunWith(Parameterized.class)
public class Testcase {

    private int myInt;

    public Testcase(int myInt) {
        this.myInt = myInt;
    }

    @Parameters(name = "{0}")
    public static Collection<Integer> data() {
        Integer[] data = new Integer[] {1,2,3,4};

        return Arrays.asList(data);
    }

    @Test
    public void test1() {
        // TODO
    }

    @Test
    public void test2() {
        // TODO
    }
}

I don't know where you got JUnitParamsRunner from. As you can see in my example, JUnit 4 defines Parameterized.

Andy
  • 1,964
  • 1
  • 15
  • 29