TestNG:如何使用DataProvider提供的数据按顺序执行多个测试方法

时间:2012-06-05 12:26:18

标签: testng dataprovider

有没有办法执行多种测试方法,以便使用来自数据提供者的不同数据?

e.g。

@DataProvider(name = "test1")
public Object[][] createData1() {
    return new Object[][] {
        { "Cedric", new Integer(36) },
        { "Anne", new Integer(37)}, 
    };
}


@Test(dataProvider = "test1")
public void verifyData1(String n1, Integer n2) {
    System.out.println(n1 + " " + n2);
}

@Test
public void verifyData2() {
    System.out.println("Verify2");
}

运行它的输出将是
塞德里克36
Verify2
安妮37
Verify2

2 个答案:

答案 0 :(得分:1)

为什么不在该类中使用多个数据提供者?

@DataProvider(name = "test1")
public Object[][] createData1() {
    return new Object[][] {
        { "Cedric", new Integer(36) },
        { "Anne", new Integer(37)}, 
    };
}

@DataProvider(name = "test2")
public Object[][] createData2() {
    return new Object[][] {
        { "Amir", new Integer(42) },
        { "Alice", new Integer(39)}, 
    };
}


@Test(dataProvider = "test1")
public void verifyData1(String n1, Integer n2) {
    System.out.println(n1 + " " + n2);
}

@Test(dataProvider = "test2")
public void verifyData2(String n1, Integer n2) {
    System.out.println(n1 + " " + n2);
}

答案 1 :(得分:0)

以下是一种方法:使用注释指定哪个方法应该接收哪些数据:

public class A {

  @DataProvider
  public Object[][] dp(Method m) {
    if (m.getAnnotation(Different.class) != null) {
      return new Object[][] {
          new Object[] { "different-a", "different-b" },
          new Object[] { "different-c", "different-d" },
        };
      } else {
        return new Object[][] {
            new Object[] { "c", "d" },
            new Object[] { "a", "b" },
        };
      }
    }

  @Test(dataProvider = "dp")
  public void test1(String a, String b) {
    System.out.println("test1: " + a + " " + b);
  }

  @Different
  @Test(dataProvider = "dp")
  public void test2(String a, String b) {
    System.out.println("test2: " + a + " " + b);
  }
}

注释:

@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target({METHOD})
public @interface Different {}

输出:

test1: c d
test1: a b
test2: different-a different-b
test2: different-c different-d