5

If you are using TestNG you would find that to use a method as a data provider you have to create a method that returns a two dimensional Object array.

So if I have a List of (say) Students , is there any utility method to convert it into a two dimensional array.

I am NOT looking to convert it manually using a loop like this

 List<Student> studentList = getStudentList();

 Object [][] objArray = new Object[studentList.size][];

 for(int i=0;i< studentList.size();i++){
    objArray[i] = new Object[1];
    objArray[i][0] = studentList.get(i);
 } 

 return objArray;

Instead I am looking at a utility function if any is available in any of the libraries.

Or a better way of writing a data provider method for TestNG

SK176H
  • 1,219
  • 2
  • 14
  • 24

4 Answers4

8

With Java 8 streams (and using this question about converting a stream into array):

@DataProvider
public Object[][] studentProvider() {
    return studentList.stream()
        .map(student -> new Object[] { student })
        .toArray(Object[][]::new);
}
alexandroid
  • 1,151
  • 2
  • 13
  • 27
3

So be it ... let stackoverflow call me a tumbleweed ... but here is the answer.

List<Student> studentList = getStudentList();

 Object [][] objArray = new Object[studentList.size][];

 for(int i=0;i< studentList.size();i++){
    objArray[i] = new Object[1];
    objArray[i][0] = studentList.get(i);
 } 

 return objArray
SK176H
  • 1,219
  • 2
  • 14
  • 24
1

This is not directly answer your question. But you can also solve that problem like this

  @DataProvider
  public Iterator<Object[]> studentProvider() {
    List<Student> students = getStudentList();
    Collection<Object[]> data = new ArrayList<Object[]>();
    students.forEach(item -> data.add(new Object[]{item}));
    return data.iterator();
  }
arulraj.net
  • 3,579
  • 2
  • 31
  • 35
1

IT worked for me in single dimension array also, I converted list to single dimension array in testng data provider, Might be useful to someone

 @DataProvider(name =  "Passing  List  Of Maps")
  public Object[]  createDataforTest3(){
   TestDataReader  testDataReader   =  new TestDataReader();
    List<String>  caselDs     =  new ArrayList<String>();
    caselDs    =             testDataReader.getValueForThekeyFromTestDataDirectory("testdate,"XYZ");
    Object[]  data      =       new String[caseIDs.size()];
    for (int  i=0;i<caseIDs.size()-1;i++)             {
   data[i]=  caselDs.get(i);
    return  data;}



  @Test(dataProvider =  "Passing  List  Of Maps",description=  "abc")
  public void  test(String value)         {
       System.out.println("Value  in  first  Map:"   + value);
     }