TestNG中的組可以從多個類中篩選組屬性相同的方法執行。#
比如有兩個類A和B,A中有1個方法a屬於組1,B中有1個方法b也屬於組1,那么我們可以通過配置TestNG文件實現把這兩個類中都屬於1組的方法抽取出來執行。
示例代碼#
car1
package ngtest;
import org.testng.annotations.Test;
public class Car1 {
@Test(groups={"driver"})//定義該方法屬於driver組
public void driverWork(){
System.out.println("car1's driver is driving");
}
@Test(groups={"boss"})//定義該方法屬於boss組
public void bossWork(){
System.out.println("car1's boss is talking");
}
}
car2
package ngtest;
import org.testng.annotations.Test;
public class Car2 {
@Test(groups={"driver"})//定義該方法屬於driver組
public void driverWork(){
System.out.println("car2's driver is driving");
}
@Test(groups={"boss"})//定義該方法屬於boss組
public void bossWork(){
System.out.println("car2's boss is talking");
}
}
配置文件testng.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<groups>
<run>
<include name="driver"/><!--篩選driver組的方法來執行-->
</run>
</groups>
<test name="Test">
<classes>
<class name="ngtest.Car1"/>
<class name="ngtest.Car2"/>
</classes>
</test>
</suite>
右鍵點擊testng.xml,選擇run as testNG suite,console輸出:
[TestNG] Running:
D:\workspace\tester\testng.xml
car1's driver is driving
car2's driver is driving
===============================================
Suite
Total tests run: 2, Failures: 0, Skips: 0
===============================================
通過上面的運行結果可以看出,配置文件中配置了兩個類Car1和Car2,通過groups標簽選擇了運行driver分組,所以兩個類中屬於該分組的方法得到了執行。
額外知識:在java代碼中,@Test(groups={"driver"})可以在大括號里指定多個組,中間用逗號分開就行。在testng.xml中<run>
標簽下還可以書寫<exclude name="abc"/>
標簽,表示不執行屬於abc組的用例。