How we can name the test case dynamically when using data provider How we can name the test case dynamically when using data provider selenium selenium

How we can name the test case dynamically when using data provider


Follow the steps below:

Step# 1:

Create a custom annotation in a separate file (ie: SetTestName.java)

@Retention(RetentionPolicy.RUNTIME)public @interface SetTestName {    int idx() default 0;}

Step# 2:

Create a base class implementing ITest interface of TestNG (TestNameSetter.java).

public class TestNameSetter implements ITest{    private String newTestName = "";    private void setTestName(String newTestName){        this.newTestName = newTestName;    }    public String getTestName() {        return newTestName;    }    @BeforeMethod(alwaysRun=true)    public void getTheNameFromParemeters(Method method, Object [] parameters){        SetTestName setTestName = method.getAnnotation(SetTestName.class);        String testCaseName = (String) parameters[setTestName.idx()];        setTestName(testCaseName);    }}

Step# 3:

Use your DataProvider like in the code snippet:

@DataProvider(name="userData") public Object[][] sampleDataProvider() {  Object[][] data = {    {"loginTestUS_Username","loginTestUSPass"},     {"loginTestIN_Username","loginTestINPass"},    {"loginTestJP_UserName","loginTestJPPass"}  };  return data; } @SetTestName(idx=0) @Test(dataProvider="userData") public void test1(String userName, String pass) {     System.out.println("Testcase 1"); } @SetTestName(idx=1) @Test(dataProvider="userData") public void test2(String userName, String pass) {     System.out.println("Testcase 2"); } 

That's all. Now, you will see your test name changed accordingly in the console.

Follow the link below for your query. I hope, you might get your desired answer here:

http://biggerwrench.blogspot.com/2014/02/testng-dynamically-naming-tests-from.html


Example for reference.

  1. Use those string like "USusername" etc. in your data provider (like "TestName1" and "TestName2" in the example) together with some other test data (like those numbers in example). Pass this name as argument to your @Factory annotated method.
  2. Make the test class implement ITest. Use the test name variable in return statement.
  3. You can split it up the way as in the example.