TestNG中的另一個有趣的功能是參數化測試。 在大多數情況下,您會遇到業務邏輯需要大量測試的場景。 參數化測試允許開發人員使用不同的值一次又一次地運行相同的測試。
TestNG可以通過兩種不同的方式將參數直接傳遞給測試方法:
使用testng.xml
使用數據提供者
下面分別介紹兩種傳參方式:
1、使用textng.xml傳送參數
范例代碼如下:
```
public class TestCase1 {
? ? @Test(enabled=true)
? ? @Parameters({"param1", "param2"})
? ? public void TestNgLearn1(String param1, int param2) {
? ? ? ? System.out.println("this is TestNG test case1, and param1 is:"+param1+"; param2 is:"+param2);
? ? ? ? Assert.assertFalse(false);
? ? }
? ??
? ? @Test(dependsOnMethods= {"TestNgLearn1"})
? ? public void TestNgLearn2() {
? ? ? ? System.out.println("this is TestNG test case2");
? ? }
}
```
xml配置:
```
<?xml version="1.0" encoding="UTF-8"?>
<suite name="Suite" parallel="false">
? <test name="Test">
? ? <parameter name="param1" value="1011111" />
? ? <parameter name="param2" value="10" />
? ? <classes>
? ? ? <class name="com.demo.test.testng.TestCase1"/>
? ? </classes>
? </test> <!-- Test -->
</suite> <!-- Suite -->
```
運行xml,結果如下:
```
this is TestNG test case1, and param1 is:1011111; param2 is:10
this is TestNG test case2
===============================================
Suite
Total tests run: 2, Failures: 0, Skips: 0
===============================================
```
2、使用@DataProvider傳遞參數
此處需要注意,傳參的類型必須要一致,且帶有@DataProvider注解的函數返回的必然是Object\[\]\[\],此處需要注意。
代碼如下:
```
public class TestCase1 {
? ? @DataProvider(name = "provideNumbers")
? ? public Object[][] provideData() {
? ? ? ? return new Object[][] { { 10, 20 }, { 100, 110 }, { 200, 210 } };
? ? }
?? ?
? ? @Test(dataProvider = "provideNumbers")
? ? public void TestNgLearn1(int param1, int param2) {
? ? ? ? System.out.println("this is TestNG test case1, and param1 is:"+param1+"; param2 is:"+param2);
? ? ? ? Assert.assertFalse(false);
? ? }
? ??
? ? @Test(dependsOnMethods= {"TestNgLearn1"})
? ? public void TestNgLearn2() {
? ? ? ? System.out.println("this is TestNG test case2");
? ? }
}
```
運行此class,結果為:
```
this is TestNG test case1, and param1 is:10; param2 is:20
this is TestNG test case1, and param1 is:100; param2 is:110
this is TestNG test case1, and param1 is:200; param2 is:210
this is TestNG test case2
PASSED: TestNgLearn1(10, 20)
PASSED: TestNgLearn1(100, 110)
PASSED: TestNgLearn1(200, 210)
PASSED: TestNgLearn2
```