有时候希望测试用例能用代码触发,发现testng支持这种操作,于是记录一下:
首先添加testng依赖:
<dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.9.10</version> </dependency>
然后实现要被调用的测试用例:
/** * testng 注解实现并发测试 */ public class ConcurrentTest { @Test(threadPoolSize = 10, invocationCount = 10, timeOut = 1000) public static void display() { System.out.println(UUID.randomUUID().toString()); } }
再用代码触发执行该测试用例:
/** * 代码触发testng测试 */ public class TestNgDemo { public static void main(String[] args) { /**初始化testNG对象*/ TestNG testNG = new TestNG(); TestListenerAdapter listener = new TestListenerAdapter(); testNG.addListener(listener); /**添加需要执行的测试类数组*/ testNG.setTestClasses(new Class[]{ConcurrentTest.class}); /**执行测试用例*/ testNG.run(); /**汇总分析*/ List<ITestResult> pass = listener.getPassedTests(); List<ITestResult> failed = listener.getFailedTests(); List<Long> interval = pass.stream().map(x -> (x.getEndMillis() - x.getStartMillis())).collect(Collectors.toList()); /**最大耗时*/ long maxtime = interval.stream().max(Comparator.naturalOrder()).get(); /**最小耗时*/ long mintime = interval.stream().min(Comparator.naturalOrder()).get(); /**平均耗时*/ double avgtime = interval.stream().mapToDouble(i -> i).average().getAsDouble(); System.out.println(String.format("test result: [success: %s],[failure: %s]",pass.size(),failed.size())); System.out.println(String.format("performance analysis: [maxtime: %s(ms)],[mintime: %s(ms),[avgtime: %s(ms)]]", maxtime, mintime, avgtime)); } }