我们可以在TestNg中创建运行时dataProvider

时间:2017-04-21 11:32:56

标签: java selenium testng testng-dataprovider

我们可以有这样的地方

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);
}

Test2的输出可以打印Test1中列表中添加的所有值吗? 我有一个情况,我需要使用从另一个测试生成的参数运行测试。请帮助。

2 个答案:

答案 0 :(得分:0)

是的,您可以按照以下说明进行操作。

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);

    }
}

答案 1 :(得分:0)

由于很少有TestNG版本,你甚至可以缩短它:

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);
  }
}

输出看起来像这样

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
===============================================