Search code examples
javatestngtestng-dataprovider

TestNG - How to pass variable's value as dataProvider name?


I have a string variable whichSet that can hold either 3 values "prd", "stg" and "int". In the Test I want to pass the value as dataProvider like this:

@Test(enabled = true, dataProvider = whichSet, dataProviderClass = TestDataProvider.class)

But i have the below error:

The value for annotation attribute Test.dataProvider must be a constant expression

I've already had 3 providers defined as:

@DataProvider(name="stg")
@DataProvider(name="prd")
@DataProvider(name="int")

Since i'm reading the data provider from another class (not in the test class), so i'm not able to pass the value to that class based on some test condition. Anyway that I can make the dataProvider = whichSet work? Thank you


Solution

  • Basically you're trying to add profile to DataProvider there should be an external parameter that should drive this. My way of solving this could be by using JVM options.

    public class Testng {
    
        @DataProvider(name = "data-provider")
        public Object[][] dataProviderMethod() {
            switch(System.getProperty("env")) {
                case "int":
                    return new Object[][] { { "int data one" }, { "data two" } };
                case "stg":
                    return new Object[][] { { "stage data one" }, { "data two" } };
                case "prod":
                    return new Object[][] { { "production data one" }, { "data two" } };
                default:
                    return new Object[][] { { "int data one" }, { "data two" } };
            }
        }
    
        @Test(enabled = true, dataProvider = "data-provider", dataProviderClass = Testng.class)
        public void test(String data) {
            System.out.println(data);
        }
    
    }
    

    And run your test using JVM system properties.

    Eclipse: enter image description here

    CLI

    java -Denv=prod -cp ".:../lib/*" org.testng.TestNG testng.xml