TestNG可以通過testng.xml和Data Providers向測驗方法傳遞引數
利用testNG.xml傳遞引數
1-創建一個TestNG測驗類
其中 parameters = {"xml-file","hostname"} 使用來接受引數的,因為有兩個值所以有兩個引數
package com.lc.testChuanCan; import org.testng.annotations.Test; public class testNG05 { @Test(parameters = {"xml-file","hostname"}) public void testNG05_01(String xmlfile,String hostname) { System.out.println("我是testNG05 類的testNG05——01方法,\n我傳遞引數是\nxml-file:"+xmlfile+"\nhostname:"+hostname); } }
2-創建一個TestNG.xml檔案
設定引數標簽
<parameter name="xml-file" value="https://www.cnblogs.com/fanfancs/p/accounts.xml"></parameter> <parameter name="hostname" value="https://www.cnblogs.com/fanfancs/p/arkonis.example.com"></parameter>
標簽:parameter
anme:相當于key ,變數名稱;對應TestNG測驗類的 parameters = {"xml-file","hostname"} 里面引數名稱,名字要一樣
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> <suite name="Suite" parallel="none"> <parameter name="xml-file" value="accounts.xml"></parameter> <parameter name="hostname" value="arkonis.example.com"></parameter> <test name="Test"> <classes> <class name="com.lc.testChuanCan.testNG05"/> </classes> </test> <!-- Test --> </suite> <!-- Suite -->
parameter也可在<test></test>里面添加引數
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<!--在測驗suit里添加引數;在這里面添加的引數測驗類都可以參考;但在test添加的引數上一級不可以使用--> <suite name="Suite" parallel="none"> <parameter name="xml-file" value="accounts.xml"></parameter> <parameter name="hostname" value="arkonis.example.com"></parameter> <test name="Test"> <classes> <class name="com.lc.testChuanCan.testNG05"/> </classes> </test> <!-- Test -->
<!-- 在test里添加引數 testKey--> <test name="test01"> <parameter name="testKey" value="我是test標簽里面的引數"></parameter> <classes> <class name="com.lc.testChuanCan.testNG6"></class> </classes> </test> </suite> <!-- Suite -->
package com.lc.testChuanCan; import org.testng.annotations.Test; public class testNG6 { //testKey引數是在test配置的,hostname是在suite里添加的都可以參考 @Test(parameters = {"testKey","hostname"}) public void textNG06_01(String testKey,String hostname) { System.out.println("我是testNG05 類的testNG06——01方法,\n我傳遞引數是\ntestKey:"+testKey+"\nhostname:"+hostname); } }
傳遞引數注釋也是使用下面方式
package com.lc.testChuanCan; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class testNG6 { //方式一 @Test(parameters = {"testKey","hostname"}) public void textNG06_01(String testKey,String hostname) { System.out.println("我是testNG6 類的testNG06——01方法,\n我傳遞引數是\ntestKey:"+testKey+"\nhostname:"+hostname); System.err.println("-----------------------------"); }
//方式二 @Parameters({"testKey","hostname"}) @Test public void textNG06_02(String testKey,String hostname) { System.out.println("我是testNG6 類的testNG06——02方法,\n我傳遞引數是\ntestKey:"+testKey+"\nhostname:"+hostname); } }

使用testNG.xml傳參存在一定的局限性:
例如只能傳輸java的基礎資料型別,如果想傳送其他的資料型別就不行了例如map
所以使用第二種方式傳值 @Parameters annotation傳遞引數
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/231792.html
標籤:其他
上一篇:做測驗一年了,該學點什么
