Search code examples
javajunitparameterizedparameterized-unit-test

Test different methods with different subset of data in JUnit test case


Say I have a JUnit test case as:

@RunWith(Parameterized.class)
public class TestMyClass {

    @Parameter
    private int expected;
    @Parameter
    private int actual;  

    @Parameters
    public static Collection<Object[]> data() {
    return Arrays.asList(new Object[][] {     
             { 0,1 }, { 1,2 }, { 2,3 }, { 3,4 }, { 4,5 }, { 5,6 },{ 6,7 }  
       });
    }

    @Test
    public void test1 { //test }

    @Test
    public void test2 { //test }

}

I want to run test1 only with {0,1}, {1,2} and {2,3} and run test2 only with {3,4}, {4,5} {5,6}

How can I achieve this?

Edit: Parameters are read at Runtime from a file.


Solution

  • Seems that there is no way you can use different sets of parameters for different tests in once class using JUnit standart '@Parameters' stuff. You can try out junit-dataprovider. It is similar to TestNG data providers. For example:

    @RunWith(DataProviderRunner.class)
    public class TestMyClass {
    
        @DataProvider
        public static Object[][] firstDataset() {
        return new Object[][] {     
                 { 3,4 }, { 4,5 }, { 5,6 },{ 6,7 }  
           };
        }
    
    
        @DataProvider
        public static Object[][] secondDataset() {
        return new Object[][] {     
                 { 3,4 }, { 4,5 }, { 5,6 },{ 6,7 }  
           };
        }
    
        @Test
        @UseDataProvider("firstDataset")
        public void test1(int a, int b) { //test }
    
        @Test
        @UseDataProvider("secondDataset")
        public void test2(int a, int b) { //test }
    
    }
    

    Or you can create 2 classes for each test.

    But I think using junit-dataprovider is more convenient.