曾经做过一需求,需要单个集成测试用例循环执行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])); } }
即通过配置文件把需要特殊处理的类和循环次数 再次进行单独设置。
具体要怎么使用,需要根据业务具体分析了
更多文章请关注公众号