1 package roger.testng; 2 3 import java.util.Random; 4 5 import org.testng.ITestContext; 6 import org.testng.annotations.DataProvider; 7 import org.testng.annotations.Test; 8 9 /* 10 * 數據提供者在方法簽名中聲明瞭一個 ITestContext 類型的參數 11 * testng 會將當前的測試上下文設置給它 12 * 13 */ 14 public class TestDataProviderITestContext { 15 @DataProvider 16 public Object[][] randomIntegers(ITestContext context) { 17 String[] groups= context.getIncludedGroups(); 18 int size = 2; 19 for (String group : groups) { 20 System.out.println("--------------" + group); 21 if (group.equals("function-test")) { 22 size = 10; 23 break; 24 } 25 } 26 27 Object[][] result = new Object[size][]; 28 Random r = new Random(); 29 for (int i = 0; i < size; i++) { 30 result[i] = new Object[] {new Integer(r.nextInt())}; 31 } 32 33 return result; 34 } 35 36 // 若是在 unite-test 組中執行, 將返回2個隨機整數構成數組; 37 // 若是在 function-test 組中執行, 將返回 10 個隨機整數構成數組 38 @Test(dataProvider = "randomIntegers", groups = {"unit-test", "function-test"}) 39 public void random(Integer n) { 40 System.out.println(n); 41 } 42 43 }
經過 testng.xml 指定運行 unite-test 組仍是 function-test 組。java