Search code examples
javaseleniumtestngtestng-dataprovider

How to store the TestNG dataprovider values in a POJO class


I have a excel sheet which has two column as look below:

enter image description here

I used @Dataprovider (TestNG annotation) to read a data from excel sheet and pass it @Test method. And test method shows like below

@Test(dataProvider = "testautomation")
    public void getData(String userName, String password)throws Exception 
      {
        System.out.println(userName+ "\t ****");
        System.out.println(password);
      }

It works as expected, and got a proper data from excel sheet. But Is there any way I can keep those two arguments in pojo class and pass the class object in @test method?. By the way I can stop exposing the arguments like (username, password in @Test method).

May be the pojo class look like below:

public class DatObject
 {
    private String userName;
    private String password;

    //and getter setter methods.
 }

And the Test method will be like below:

@Test(dataProvider = "testautomation")
        public void getData(DataObject dataObj)throws Exception 
          {

            System.out.println(dataObj.getUserName()+ "\t ****");
            System.out.println(dataObj.getPasswrod());
          }

I want to call this pojo class object as argument in @test method, and using getter and setter methods in pojo class used to get values instead of passing username, and password in @Test method.

Any leads?


Solution

  • Your data provider method should return pojos:

    @DataProvider(name = "pojoProvider")
    public Object[][] createPojoData() {
     return new Object[][] {
       { new DataObject("User1", "****") },
       { new DataObject("User2", "****") },
     };
    }
    

    Then just specify it in test annotation:

    @Test(dataProvider = "pojoProvider")
    public void getData(DataObject dataObj)throws Exception 
    {
        System.out.println(dataObj.getUserName()+ "\t ****");
        System.out.println(dataObj.getPasswrod());
    }