用代碼觸發testng實現並發測試


有時候希望測試用例能用代碼觸發,發現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)); } }

最后執行結果如下:

[TestNG] Running:
  Command line suite

894eecc7-6d39-4b8d-bc6f-36c94296ff13 f7bdeb99-2baf-4894-a0a3-40fd0792432a ce27be2e-402b-46bb-8b71-c983f2d3b36c 4b042268-ede8-4c75-9d9a-e5ea7cf63d93 a2dd8b48-56e9-4187-b2f8-004a99164b3c b4d188e2-1ba4-4635-a546-7131faa2dede cbffc694-f0f5-48e3-80ec-e9cebdb054b9 904eaab1-3ef7-4627-bc6c-0e890510b119 3db7eb16-f369-449c-be2c-cb89e9647ad0 c4baf3ce-a162-40e0-aa27-e538cc09fb99 =============================================== Command line suite Total tests run: 10, Failures: 0, Skips: 0 =============================================== test result: [success: 10],[failure: 0] performance analysis: [maxtime: 8(ms)],[mintime: 0(ms),[avgtime: 2.8(ms)]] Process finished with exit code 0

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM