曾經做過一需求,需要單個集成測試用例循環執行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])); } }
即通過配置文件把需要特殊處理的類和循環次數 再次進行單獨設置。
具體要怎么使用,需要根據業務具體分析了