0

Can we have something like this where

public class NewTest {
private List<String> id= new ArrayList<String>();

@Test
public void Test1() {

    id.add("First Value");
    id.add("Second Value");
    id.add("Third Value");
    id.add("Fourth Value");

    System.out.println("Added all the data to the list");
}

@DataProvider
public Object[][] dp() {
    Object[][] returnData= new String[1][];

    for (int i=0; i<id.size();i++){
        returnData[0][i]=id.get(i);
    }

    return returnData;
}


@Test(dataProvider = "dp", priority=1)
public void Test2(String s) {

    System.out.println(s);
}

Output of Test2 could print all the values added in the List in Test1? I have a situation and I need to run test with parameters generated from another test. Kindly help.

NiNa
  • 111
  • 1
  • 4

2 Answers2

0

Yes you can do it as mentioned below.

import java.util.ArrayList;
import java.util.List;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class runTimeDataProvider {

    private List<String> id= new ArrayList<String>();

    @Test
    public void Test1() {

        id.add("First Value");
        id.add("Second Value");
        id.add("Third Value");
        id.add("Fourth Value");

        System.out.println("Added all the data to the list");
    }

    @DataProvider
    public Object[][] dp() {
        Object[][] returnData= new String[1][4];

        for (int i=0; i<id.size();i++){
            returnData[0][i]=id.get(i);
            System.out.println(returnData[0][i]);
        }

        return returnData;
    }


    @Test(dataProvider = "dp", priority=1)
    public void Test2(String s1,String s2,String s3,String s4) {

        System.out.println(s1+" "+s2+" "+s3+" "+s4);

    }
}
Akarsh
  • 967
  • 5
  • 9
0

Since few TestNG version, you can even make it shorter:

public class RunTimeDataProvider {

  private final List<String> id = new ArrayList<>();

  @Test
  public void test1() {
    id.add("First Value");
    id.add("Second Value");
    id.add("Third Value");
    id.add("Fourth Value");

    System.out.println("Added all the data to the list");
  }

  @DataProvider
  public Iterator<String> dp() {
    return id.iterator();
  }

  @Test(dataProvider = "dp", dependsOnMethods = "test1")
  public void test2(String s) {
    System.out.println(s);
  }
}

The output looks like this

Added all the data to the list
First Value
Second Value
Third Value
Fourth Value
PASSED: test1
PASSED: test2("First Value")
PASSED: test2("Second Value")
PASSED: test2("Third Value")
PASSED: test2("Fourth Value")

===============================================
    Default test
    Tests run: 5, Failures: 0, Skips: 0
===============================================


===============================================
Default suite
Total tests run: 5, Failures: 0, Skips: 0
===============================================
jithinkmatthew
  • 890
  • 8
  • 17
juherr
  • 5,640
  • 1
  • 21
  • 63