JUnit parameterized test with varying parameters

570 Views Asked by At

Consider a parameterized JUnit test. JUnit provides a way to parameterize such a test using a static method:

@Parameterized.Parameters
    public static Collection<Object[]> parameters(){
        Object[][] data = new Object[][] { { 1, 11 }, { 2, 22 }, { 3, 33 }, { 4, 44 } };
        return Arrays.asList(data);
    }

However, this is not what I need, because I do not know the parameters at the test class itself. The test class should simply be a test class that can be parameterized with a set of parameters. I do not want to specify such parameters inside the class itself. Consider I have a lot of such classes in a test suite.

What I want to be able is to parameterizes the whole test suite from external code. I.e., have some other code that instanciates the suite with a specific set of parameters. The suite itself does not know the parameters with which it will be parameterized.

E.g., I have a test suite X consisting of the test classes A, B, and C. All these classes take, e.g., a String and an integer in their constructor as their parameters. Now I want so be able to instanciate X externally (e.g., in another test suite) with a specific String s and int i so that it will instanciate A B and C using s and i in their constructors.

How can this be achieved?

1

There are 1 best solutions below

0
On

I'm using the JUnitParams package, which adds more abilities to parametrize tests. One of those abilities, is to specify a separate class that provides the parameters. Take a look at the link, they give a lot of examples, one of them is using an external class.