Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How we can name the test case dynamically when using data provider, for example:

If I have a login test case, and I want use data provider for different user name and password, where each user represent a country, how I will have the output of test failed or pass but with different test case name for instance I should have like this:

loginTestUSusername pass
loginTestINusername pass
loginTestJPuserName pass

Note that the name of the method is loginTest, and the appended USusername,INusername,JPusername are the test data from the data provider

like image 677
BeniHassenWolf Avatar asked Oct 18 '22 13:10

BeniHassenWolf


1 Answers

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

like image 149
optimistic_creeper Avatar answered Oct 21 '22 06:10

optimistic_creeper