曾經做過一需求,需要單個內建測試用例循環執行N次,或許你會說for循環就可以了,這當然是可以的。那有沒有逼格更高點的方法,當然也是有的。下面我們就說下使用TestNG注解功能實作用例的循環執行。
1、直接使用注解
//invocationCount 即表示該用例循環執行多少次
@Test(invocationCount = 3)
public void test() {
System.err.println("1222");
}
該方法有一個弊端,如果用例比較多,修改循環次數就會比較麻煩,需要一個一個去修改。
2、使用監聽功能
2.1、實作監聽接口
/**
* 實作IAnnotationTransformer 接口
* @author houlandong
*
*/
public class RetryListener implements IAnnotationTransformer{
@Override
public void transform(ITestAnnotation annotation, Class testClass,
Constructor testConstructor, Method testMethod) {
//統一設定循環次數
annotation.setInvocationCount(5);
}
}
2.2、配置監聽
<suite name="TradeTest" preserve-order="true" parallel="false"
thread-count="5" annotations="javadoc" skipfailedinvocationcounts="true"
configfailurepolicy="continue">
<test name="TradeTest" verbose="2" preserve-order="true" parallel="false"
thread-count="5" annotations="javadoc" group-by-instances="false"
skipfailedinvocationcounts="true" configfailurepolicy="continue">
<classes>
<!--需要執行的用例-->
<class name="com.enniu.cloud.services.tmsdefender.util.Leohou" />
</classes>
</test>
<listeners>
<!--實作的監聽接口-->
<listener class-name="com.enniu.cloud.services.tmsdefender.util.RetryListener" />
</listeners>
</suite>
注意:
1、該方法需要配合mvn test和testng.xml(TestNG的靈魂,可以自行百度進行更多的了解) 一起使用,在xml檔案中配置我們實作的監聽,這樣就統一配置了該suite包含的所有用例的循環次數。
2、監聽設定的優先級> 直接使用注解的方式,是以該方法不友善設定某一個用例的循環次數。
我是通過配置檔案來實作的
// 統一設定循環次數
annotation.setInvocationCount(5);
// 設定 需要特殊處理方法的循環次數
String excepLoopCount = property.getProperty("excepLoopCount");
String[] excepCount = excepLoopCount.split(";");
for (int i = 0; i < excepCount.length; i++) {
String[] temp = excepCount[i].split(",");
if (testMethod.getName().equals(temp[0])) {
LogUtil.info("該方法循環" + temp[1] + "次");
annotation.setInvocationCount(Integer.valueOf(temp[1]));
}
}
即通過配置檔案把需要特殊處理的類和循環次數 再次進行單獨設定。
具體要怎麼使用,需要根據業務具體分析了