When we want to pass an object in TestNg data provider we use to follow the below steps.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.dokimi.tests.ui; | |
import org.testng.annotations.DataProvider; | |
import org.testng.annotations.Test; | |
public class TestClass { | |
private String dob = "xyz"; | |
public String getDob() { | |
return dob; | |
} | |
@DataProvider | |
public Object[][] test() { | |
TestClass test = new TestClass(); | |
return new Object[][]{ | |
{"prem", "kumar", test} | |
}; | |
} | |
@Test(dataProvider = "test") | |
public void testing(String firstname, String secondName, TestClass test) { | |
System.out.println("First Name::" + firstname); | |
System.out.println("Second Name::" + secondName); | |
System.out.println("Test Object::" + test.getDob()); | |
} | |
} | |
But This can be rewritten in this way for a cleaner code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.dokimi.tests.ui; | |
import org.testng.annotations.DataProvider; | |
import org.testng.annotations.Test; | |
import java.util.ArrayList; | |
import java.util.Iterator; | |
import java.util.List; | |
public class TestClass { | |
private String dob = "xyz"; | |
public String getDob() { | |
return dob; | |
} | |
@DataProvider | |
public Iterator<Object[]> test() { | |
List<Object[]> list = new ArrayList<>(); | |
TestClass test = new TestClass(); | |
for(int i=0;i<3;i++) { | |
list.add(new Object[]{"prem"+i,"kumar"+i,test}); | |
} | |
return list.iterator(); | |
} | |
@Test(dataProvider = "test") | |
public void testing(String firstname, String secondName, TestClass test) { | |
System.out.println("First Name::" + firstname); | |
System.out.println("Second Name::" + secondName); | |
System.out.println("Test Object::" + test.getDob()); | |
} | |
} | |