溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

java中TestNG使用是怎樣的

發(fā)布時間:2021-12-18 10:18:31 來源:億速云 閱讀:193 作者:柒染 欄目:開發(fā)技術

java中TestNG使用是怎樣的,相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

    一、TestNG介紹

    TestNG是Java中的一個測試框架, 類似于JUnit 和NUnit, 功能都差不多, 只是功能更加強大,使用也更方便。
    詳細使用說明請參考官方鏈接:https://testng.org/doc/index.html

    二、TestNG安裝(基于eclipse+maven)

    工程的pom.xml中需要添加如下內(nèi)容:

    <dependency>
          <groupId>org.testng</groupId>
          <artifactId>testng</artifactId>
          <version>6.10</version>
          <scope>test</scope>
        </dependency>

    記得Maven install一下
    eclipse中的TestNG插件的安裝則需要在Help中做,地址為http://beust.com/eclipse;有時候會打不開網(wǎng)址,本文提供一下本地下載地址:http://www.kemok4.com/softs/575355.html

    三、TestNG基本使用和運行

    新建一個maven工程,新建一個TestNG的class,可以直接新建一個class來使用,也可以新建一個TestNG的class,如下圖所示:

    java中TestNG使用是怎樣的

    此方法好處在于你在創(chuàng)建class的時候可以直接把注解的各個方法都加進去,同時也可以創(chuàng)建xml,名字路徑可以自己定義,注意xml文件的路徑是支持相對路徑的,出來的class文件如下所示:

    package com.demo.test.testng;
    
    import org.testng.annotations.Test;
    
    public class NewTest {
    	
      @Test
      public void f() {
    	  
      }
    }

    一個簡單的用例如下:

    package com.demo.test.testng;
    
    import org.testng.Assert;
    import org.testng.annotations.Test;
    
    public class NewTest {
    	
      @Test
      public void f() {
    	  System.out.println("this is new test");
    	  Assert.assertTrue(true);
      }
    }

    1、直接運行:

    java中TestNG使用是怎樣的

    結果如下:

    [RemoteTestNG] detected TestNG version 6.10.0
    [TestNG] Running:
    C:\Users\aaa\AppData\Local\Temp\testng-eclipse-342998054\testng-customsuite.xml

    this is new test
    PASSED: f

    ===============================================
    Default test
    Tests run: 1, Failures: 0, Skips: 0
    ===============================================


    ===============================================
    Default suite
    Total tests run: 1, Failures: 0, Skips: 0
    ===============================================

    [TestNG] Time taken by org.testng.reporters.JUnitReportReporter@64bfbc86: 4 ms
    [TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@7e0b0338: 26 ms
    [TestNG] Time taken by org.testng.reporters.jq.Main@7fac631b: 20 ms
    [TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 0 ms
    [TestNG] Time taken by org.testng.reporters.XMLReporter@23e028a9: 3 ms
    [TestNG] Time taken by org.testng.reporters.EmailableReporter2@578486a3: 2 ms

    2、xml方式運行

    由于我將xml放置在其他文件夾,不和class放在一個文件夾,所以需要修改xml,如下所示:

    <?xml version="1.0" encoding="UTF-8"?>
    <suite name="Suite" parallel="false">
      <test name="Test">
        <classes>
          <class name="com.demo.test.testng.NewTest"/>
        </classes>
      </test> <!-- Test -->
    </suite> <!-- Suite -->

    運行方法:
    右鍵該xml選擇Run As–>TestNG Suite,如下:

    java中TestNG使用是怎樣的

    運行結果如下:

    [RemoteTestNG] detected TestNG version 6.10.0
    [TestNGContentHandler] [WARN] It is strongly recommended to add "<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >" at the top of your file, otherwise TestNG may fail or not work as expected.
    [XmlSuite] [WARN] 'parallel' value 'false' is deprecated, default value will be used instead: 'none'.
    [TestNG] Running:
    D:\software\workspace\testng\src\main\java\com\demo\test\testCase\newTestXML.xml

    this is new test

    ===============================================
    Suite
    Total tests run: 1, Failures: 0, Skips: 0
    ===============================================

    四、注解說明

    TestNG支持多種注解,可以進行各種組合,如下進行簡單的說明

    注解描述
    @BeforeSuite在該套件的所有測試都運行在注釋的方法之前,僅運行一次
    @AfterSuite在該套件的所有測試都運行在注釋方法之后,僅運行一次
    @BeforeClass在調(diào)用當前類的第一個測試方法之前運行,注釋方法僅運行一次
    @AfterClass在調(diào)用當前類的第一個測試方法之后運行,注釋方法僅運行一次
    @BeforeTest注釋的方法將在屬于test標簽內(nèi)的類的所有測試方法運行之前運行
    @AfterTest注釋的方法將在屬于test標簽內(nèi)的類的所有測試方法運行之后運行
    @BeforeGroups配置方法將在之前運行組列表。 此方法保證在調(diào)用屬于這些組中的任何一個的第一個測試方法之前不久運行
    @AfterGroups此配置方法將在之后運行組列表。該方法保證在調(diào)用屬于任何這些組的最后一個測試方法之后不久運行
    @BeforeMethod注釋方法將在每個測試方法之前運行
    @AfterMethod注釋方法將在每個測試方法之后運行
    @DataProvider標記一種方法來提供測試方法的數(shù)據(jù)。 注釋方法必須返回一個Object [] [],其中每個Object []可以被分配給測試方法的參數(shù)列表。 要從該DataProvider接收數(shù)據(jù)的@Test方法需要使用與此注釋名稱相等的dataProvider名稱
    @Factory將一個方法標記為工廠,返回TestNG將被用作測試類的對象。 該方法必須返回Object []
    @Listeners定義測試類上的偵聽器
    @Parameters描述如何將參數(shù)傳遞給@Test方法
    @Test將類或方法標記為測試的一部分,此標記若放在類上,則該類所有公共方法都將被作為測試方法

    如上列表中的@Factory、@Linsteners這兩個是不常用的;
    前十個注解看起來不太容易區(qū)分,順序不太容易看明白,以如下范例做簡單說明,代碼:

    import org.testng.Assert;
    import org.testng.annotations.AfterClass;
    import org.testng.annotations.AfterGroups;
    import org.testng.annotations.AfterMethod;
    import org.testng.annotations.AfterSuite;
    import org.testng.annotations.AfterTest;
    import org.testng.annotations.BeforeClass;
    import org.testng.annotations.BeforeGroups;
    import org.testng.annotations.BeforeMethod;
    import org.testng.annotations.BeforeSuite;
    import org.testng.annotations.BeforeTest;
    import org.testng.annotations.Test;
    
    public class NewTest {
    
      @Test(groups="group1")
      public void test1() {
    	  System.out.println("test1 from group1");
    	  Assert.assertTrue(true);
      }
      
      @Test(groups="group1")
      public void test11() {
    	  System.out.println("test11 from group1");
    	  Assert.assertTrue(true);
      }
      
      @Test(groups="group2")
      public void test2() 
      {
    	  System.out.println("test2 from group2");
    	  Assert.assertTrue(true);
      }
      
      @BeforeTest
      public void beforeTest() 
      {
    	  System.out.println("beforeTest");
      }
      
      @AfterTest
      public void afterTest() 
      {
    	  System.out.println("afterTest");
      }
      
      @BeforeClass
      public void beforeClass() 
      {
    	  System.out.println("beforeClass");
      }
      
      @AfterClass
      public void afterClass() 
      {
    	  System.out.println("afterClass");
      }
      
      @BeforeSuite
      public void beforeSuite() 
      {
    	  System.out.println("beforeSuite");
      }
      
      @AfterSuite
      public void afterSuite() 
      {
    	  System.out.println("afterSuite");
      }
      
      //只對group1有效,即test1和test11
      @BeforeGroups(groups="group1")
      public void beforeGroups() 
      {
    	  System.out.println("beforeGroups");
      }
      
      //只對group1有效,即test1和test11
      @AfterGroups(groups="group1")
      public void afterGroups() 
      {
    	  System.out.println("afterGroups");
      }
      
      @BeforeMethod
      public void beforeMethod() 
      {
    	  System.out.println("beforeMethod");
      }
      
      @AfterMethod
      public void afterMethod() 
      {
    	  System.out.println("afterMethod");
      }
    }

    運行結果如下:

    beforeSuite
    beforeTest
    beforeClass
    beforeGroups
    beforeMethod
    test1 from group1
    afterMethod
    beforeMethod
    test11 from group1
    afterMethod
    afterGroups
    beforeMethod
    test2 from group2
    afterMethod
    afterClass
    afterTest
    PASSED: test1
    PASSED: test11
    PASSED: test2

    ===============================================
    Default test
    Tests run: 3, Failures: 0, Skips: 0
    ===============================================

    afterSuite

    對照前面的說明應該就可以能比較明白了。

    五、TestNG斷言

    TestNG的斷言種類很多,包括相等/不相等,true/false、為null/不為null、相同/不相同等。

    六、TestNG預期異常測試

    預期異常測試通過在@Test注解后加入預期的Exception來進行添加,范例如下所示:

    @Test(expectedExceptions = ArithmeticException.class)
        public void divisionWithException() {
            int i = 1 / 0;
            System.out.println("After division the value of i is :"+ i);
        }

    運行結果如下:

    [RemoteTestNG] detected TestNG version 6.10.0
    [TestNG] Running:
    C:\Users\Administrator\AppData\Local\Temp\testng-eclipse--754789457\testng-customsuite.xml

    PASSED: divisionWithException

    ===============================================
    Default test
    Tests run: 1, Failures: 0, Skips: 0
    ===============================================


    ===============================================
    Default suite
    Total tests run: 1, Failures: 0, Skips: 0
    ===============================================

    [TestNG] Time taken by org.testng.reporters.JUnitReportReporter@55d56113: 0 ms
    [TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@1e127982: 0 ms
    [TestNG] Time taken by org.testng.reporters.jq.Main@6e0e048a: 32 ms
    [TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 0 ms
    [TestNG] Time taken by org.testng.reporters.XMLReporter@43814d18: 0 ms
    [TestNG] Time taken by org.testng.reporters.EmailableReporter2@6ebc05a6: 0 ms

    七、TestNG忽略測試

    有時候我們寫的用例沒準備好,或者該次測試不想運行此用例,那么刪掉顯然不明智,那么就可以通過注解@Test(enabled = false)來將其忽略掉,此用例就不會運行了,如下范例:

    import org.testng.annotations.Test;
    
    public class TestCase1 {
    
        @Test(enabled=false)
        public void TestNgLearn1() {
            System.out.println("this is TestNG test case1");
        }
        
        @Test
        public void TestNgLearn2() {
            System.out.println("this is TestNG test case2");
        }
    }

    運行結果:

    this is TestNG test case2
    PASSED: TestNgLearn2

    八、TestNG超時測試

    “超時”表示如果單元測試花費的時間超過指定的毫秒數(shù),那么TestNG將會中止它并將其標記為失敗。此項常用于性能測試。如下為一個范例:

    import org.testng.annotations.Test;
    
    public class TestCase1 {
    
        @Test(timeOut = 5000) // time in mulliseconds
        public void testThisShouldPass() throws InterruptedException {
            Thread.sleep(4000);
        }
    
        @Test(timeOut = 1000)
        public void testThisShouldFail() {
            while (true){
                // do nothing
            }
    
        }
    }

    結果如下:

    PASSED: testThisShouldPass
    FAILED: testThisShouldFail
    org.testng.internal.thread.ThreadTimeoutException: Method com.demo.test.testng.TestCase1.testThisShouldFail() didn't finish within the time-out 1000
    at com.demo.test.testng.TestCase1.testThisShouldFail(TestCase1.java:37)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:104)
    at org.testng.internal.InvokeMethodRunnable.runOne(InvokeMethodRunnable.java:54)
    at org.testng.internal.InvokeMethodRunnable.run(InvokeMethodRunnable.java:44)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

    九、分組測試

    分組測試即為使用group,如果你使用xml的話就是里邊的<groups>標簽,如果是直接在class中,是通過@Test(groups="group2")這種方式來分組,如第四節(jié)的注解說明中的那個例子,分了兩個group,而且@BeforeGroup是需要添加group名稱才可以正確掛載到該group下的;
    這個group說明可以是在單個的測試方法上,也可以在class上,只要具有同樣的group名稱都會在同一個group中,同時group名稱可以有多個,類似@Test(groups = {"mysql","database"})這種,范例如下:
    一個測試文件NewTest.class:

    public class NewTest {
    
      @Test(groups="group1")
      public void test1() {
    	  System.out.println("test1 from group1");
    	  Assert.assertTrue(true);
      }
      
      @Test(groups="group1")
      public void test11() {
    	  System.out.println("test11 from group1");
    	  Assert.assertTrue(true);
      }
      
      @Test(groups="group2")
      public void test2() 
      {
    	  System.out.println("test2 from group2");
    	  Assert.assertTrue(true);
      }
      
      @BeforeTest
      public void beforeTest() 
      {
    	  System.out.println("beforeTest");
      }
      
      @AfterTest
      public void afterTest() 
      {
    	  System.out.println("afterTest");
      }
      
      @BeforeClass
      public void beforeClass() 
      {
    	  System.out.println("beforeClass");
      }
      
      @AfterClass
      public void afterClass() 
      {
    	  System.out.println("afterClass");
      }
      
      @BeforeSuite
      public void beforeSuite() 
      {
    	  System.out.println("beforeSuite");
      }
      
      @AfterSuite
      public void afterSuite() 
      {
    	  System.out.println("afterSuite");
      }
      
      @BeforeGroups(groups="group1")
      public void beforeGroups() 
      {
    	  System.out.println("beforeGroups");
      }
      
      @AfterGroups(groups="group1")
      public void afterGroups() 
      {
    	  System.out.println("afterGroups");
      }
      
      @BeforeMethod
      public void beforeMethod() 
      {
    	  System.out.println("beforeMethod");
      }
      
      @AfterMethod
      public void afterMethod() 
      {
    	  System.out.println("afterMethod");
      }
      
    }

    另一個TestCase1.class:

    @Test(groups= "group2")
    public class TestCase1 {
    
        @Test(enabled=false)
        public void TestNgLearn1() {
            System.out.println("this is TestNG test case1");
        }
        
        @Test
        public void TestNgLearn2() {
            System.out.println("this is TestNG test case2");
        }
    }

    xml如下:

    <?xml version="1.0" encoding="UTF-8"?>
    <suite name="Suite" parallel="false">
      <test name="Test">
        <groups>
          <incloud name="group1"></incloud>
          <incloud name="group2"></incloud>
        </groups>
        <classes>
          <class name="com.demo.test.testng.NewTest"/>
          <class name="com.demo.test.testng.TestCase1"/>
        </classes>
      </test> <!-- Test -->
    </suite> <!-- Suite -->

    運行結果如下:

    beforeSuite
    beforeTest
    beforeClass
    beforeGroups
    beforeMethod
    test1 from group1
    afterMethod
    beforeMethod
    test11 from group1
    afterMethod
    afterGroups
    beforeMethod
    test2 from group2
    afterMethod
    afterClass
    this is TestNG test case2
    afterTest
    afterSuite

    如上所示,先運行了group1的兩個用例,再運行group2的兩條用例;
    注意在xml標識group,需要將要運行的group加進來,同時還要將被標識這些group的class也加進來,不被加進去的不會運行;

    十、分suite測試

    測試套件是用于測試軟件程序的行為或一組行為的測試用例的集合。 在TestNG中,我們無法在測試源代碼中定義一個套件,但它可以由一個XML文件表示,因為套件是執(zhí)行的功能。 它還允許靈活配置要運行的測試。 套件可以包含一個或多個測試,并由<suite>標記定義。<suite>是testng.xml的根標記。 它描述了一個測試套件,它又由幾個<test>部分組成。
    下表列出了<suite>接受的所有定義的合法屬性。

    屬性描述
    name套件的名稱,這是一個強制屬性
    verbose運行的級別或詳細程度,級別為0-10,其中10最詳細
    parallelTestNG是否運行不同的線程來運行這個套件,默認為none,其他級別為methods、tests、classes、instances
    thread-count如果啟用并行模式(忽略其他方式),則為使用的線程數(shù)
    annotations在測試中使用的注釋類型
    time-out在本測試中的所有測試方法上使用的默認超時

    十一、依賴測試

    有時,我們可能需要以特定順序調(diào)用測試用例中的方法,或者可能希望在方法之間共享一些數(shù)據(jù)和狀態(tài)。 TestNG支持這種依賴關系,因為它支持在測試方法之間顯式依賴的聲明。
    TestNG允許指定依賴關系:

    • @Test注釋中使用屬性dependsOnMethods

    • @Test注釋中使用屬性dependsOnGroups

    除此之外依賴還分為hard依賴和soft依賴:

    • hard依賴:默認為此依賴方式,即其所有依賴的methods或者groups必須全部pass,否則被標識依賴的類或者方法將會被略過,在報告中標識為skip,如后面的范例所示,此為默認的依賴方式;

    • soft依賴:此方式下,其依賴的方法或者組有不是全部pass也不會影響被標識依賴的類或者方法的運行,注意如果使用此方式,則依賴者和被依賴者之間必須不存在成功失敗的因果關系,否則會導致用例失敗。此方法在注解中需要加入alwaysRun=true即可,如@Test(dependsOnMethods= {"TestNgLearn1"}, alwaysRun=true)

    在TestNG中,我們使用dependOnMethods和dependsOnGroups來實現(xiàn)依賴測試。且這兩個都支持正則表達式,如范例三所示,如下為幾個使用范例:

    范例一,被依賴方法pass:

    public class TestCase1 {
    
        @Test(enabled=true)
        public void TestNgLearn1() {
            System.out.println("this is TestNG test case1");
        }
        
        @Test(dependsOnMethods= {"TestNgLearn1"})
        public void TestNgLearn2() {
            System.out.println("this is TestNG test case2");
        }
    }

    運行結果:

    this is TestNG test case1
    this is TestNG test case2
    PASSED: TestNgLearn1
    PASSED: TestNgLearn2

    范例二,被依賴方法fail:

    public class TestCase1 {
    
        @Test(enabled=true)
        public void TestNgLearn1() {
            System.out.println("this is TestNG test case1");
            Assert.assertFalse(true);
        }
        
        @Test(dependsOnMethods= {"TestNgLearn1"})
        public void TestNgLearn2() {
            System.out.println("this is TestNG test case2");
        }
    }

    結果:

    this is TestNG test case1
    FAILED: TestNgLearn1
    junit.framework.AssertionFailedError
    at junit.framework.Assert.fail(Assert.java:47)
    at junit.framework.Assert.assertTrue(Assert.java:20)
    at junit.framework.Assert.assertFalse(Assert.java:34)
    at junit.framework.Assert.assertFalse(Assert.java:41)
    at com.demo.test.testng.TestCase1.TestNgLearn1(TestCase1.java:26)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:104)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:645)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:851)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1177)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
    at org.testng.TestRunner.privateRun(TestRunner.java:756)
    at org.testng.TestRunner.run(TestRunner.java:610)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:387)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:382)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
    at org.testng.SuiteRunner.run(SuiteRunner.java:289)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1293)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1218)
    at org.testng.TestNG.runSuites(TestNG.java:1133)
    at org.testng.TestNG.run(TestNG.java:1104)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)

    SKIPPED: TestNgLearn2

    范例三、group依賴:
    如下所示,method1依賴group名稱為init的所有方法:

    @Test(groups = { "init" })
    public void serverStartedOk() {}
     
    @Test(groups = { "init" })
    public void initEnvironment() {}
     
    @Test(dependsOnGroups = { "init.*" })
    public void method1() {}

    這里init這個group中的兩個方法的執(zhí)行順序如果沒有在xml中指明則每次運行的順序不能保證

    十二、參數(shù)化測試

    TestNG中的另一個有趣的功能是參數(shù)化測試。 在大多數(shù)情況下,您會遇到業(yè)務邏輯需要大量測試的場景。 參數(shù)化測試允許開發(fā)人員使用不同的值一次又一次地運行相同的測試。
    TestNG可以通過兩種不同的方式將參數(shù)直接傳遞給測試方法:

    • 使用testng.xml

    • 使用數(shù)據(jù)提供者

    下面分別介紹兩種傳參方式:

    1、使用textng.xml傳送參數(shù)

    范例代碼如下:

    public class TestCase1 {
    
        @Test(enabled=true)
        @Parameters({"param1", "param2"})
        public void TestNgLearn1(String param1, int param2) {
            System.out.println("this is TestNG test case1, and param1 is:"+param1+"; param2 is:"+param2);
            Assert.assertFalse(false);
        }
        
        @Test(dependsOnMethods= {"TestNgLearn1"})
        public void TestNgLearn2() {
            System.out.println("this is TestNG test case2");
        }
    }

    xml配置:

    <?xml version="1.0" encoding="UTF-8"?>
    <suite name="Suite" parallel="false">
      <test name="Test">
        <parameter name="param1" value="1011111" />
        <parameter name="param2" value="10" />
        <classes>
          <class name="com.demo.test.testng.TestCase1"/>
        </classes>
      </test> <!-- Test -->
    </suite> <!-- Suite -->

    運行xml,結果如下:

    this is TestNG test case1, and param1 is:1011111; param2 is:10
    this is TestNG test case2

    ===============================================
    Suite
    Total tests run: 2, Failures: 0, Skips: 0
    ===============================================

    2、使用@DataProvider傳遞參數(shù)

    此處需要注意,傳參的類型必須要一致,且?guī)в?code>@DataProvider注解的函數(shù)返回的必然是Object[][],此處需要注意。
    代碼如下:

    public class TestCase1 {
    
        @DataProvider(name = "provideNumbers")
        public Object[][] provideData() {
    
            return new Object[][] { { 10, 20 }, { 100, 110 }, { 200, 210 } };
        }
    	
        @Test(dataProvider = "provideNumbers")
        public void TestNgLearn1(int param1, int param2) {
            System.out.println("this is TestNG test case1, and param1 is:"+param1+"; param2 is:"+param2);
            Assert.assertFalse(false);
        }
        
        @Test(dependsOnMethods= {"TestNgLearn1"})
        public void TestNgLearn2() {
            System.out.println("this is TestNG test case2");
        }
    }

    運行此class,結果為:

    this is TestNG test case1, and param1 is:10; param2 is:20
    this is TestNG test case1, and param1 is:100; param2 is:110
    this is TestNG test case1, and param1 is:200; param2 is:210
    this is TestNG test case2
    PASSED: TestNgLearn1(10, 20)
    PASSED: TestNgLearn1(100, 110)
    PASSED: TestNgLearn1(200, 210)
    PASSED: TestNgLearn2

    十三、XML配置文件說明

    前面講的大多都是以測試腳本為基礎來運行的,少部分是以xml運行,這里以xml來講解下:

    <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
    <suite name="SuiteName" verbose="1" >

    如下分別講解各個標簽:

    1、suite標簽

    testNG.xml文件的最外層標簽即suite,即測試套件,其下可以有多個<test><groups>,其有幾個可以添加的屬性在第十節(jié)的分suite測試中有做說明,這里做下詳細說明:

    (1)、name屬性

    此屬性屬于必須要有的,值可以自行設定,此名字會在testNG的報告中看到;

    (2)、verbose屬性

    此屬性為指定testNG報告的詳細程度,從0開始到10,其中10為最詳細,默認生成的xml此屬性值為1;

    (3)、parallel屬性

    此屬性是指代運行方式,默認為none,即串行運行方式;并行執(zhí)行方法包括如下幾種,下面做分別說明:

    methods:方法層級,若為此值,則該suite下所有的測試方法都將進行多線程,即測試用例級別的多線程。如果用例之間有依賴,則執(zhí)行順序會按照設定的依賴來運行;

    <suite name="My suite" parallel="methods" thread-count="5">

    tests:TestNG將在同一線程中運行相同的<Test>標簽中的所有方法,每個<test>標簽都將處于一個單獨的線程中,這允許您將不是線程安全的所有類分組在同一個<test>中,并保證它們都將在同一個線程中運行,同時利用TestNG使用盡可能多的線程運行測試。

    <suite name="My suite" parallel="tests" thread-count="5">

    classes:類級別并發(fā),即TestNG會將該suite下每個class都將在單獨的線程中運行,同一個class下的所有用例都將在同一個線程中運行;

    <suite name="My suite" parallel="classes" thread-count="5">

    instances:實例級別,即TestNG將在同一線程中運行同一實例中的所有方法,兩個不同實例上的兩個方法將在不同的線程中運行。

    <suite name="My suite" parallel="instances" thread-count="5">

    (4)、thread-count屬性

    此屬性用于指定線程數(shù),按照需要輸入,需要parallel參數(shù)非none時才可以添加;

    (5)、annotations屬性

    此項為注解的級別,為methods級別和class級別,一般不用設置;

    (6)、time-out屬性

    此屬性用于指定超時時間,該suite下所有的用例的超時時間;

    (7)、group-by-instances屬性

    此項用于那些有依賴的方法,且被依賴的對象有多個重載對象,因為如果是依賴方法,且該方法有多個重載方法,則默認是會將所有重載方法都跑完再運行被依賴方法,但有時候我們不想這樣,則將此項設置為true即可;

    (8)、preserve-order屬性

    值可輸入true或者false,如果為true,則用例執(zhí)行會按照在xml中的順序執(zhí)行,否則會亂序執(zhí)行,不添加此屬性的話默認是按順序執(zhí)行的;

    2、test標簽

    此標簽無特別意義,其下可以包括多個標簽,如groups、classes等,如下介紹下幾種書寫方式:

    選擇一個包中的全部測試腳本(包含子包)

    <test name = "allTestsInAPackage" >
       <packages>
          <package name = "whole.path.to.package.* />
       </packages>
    </test>

    選擇一個類中的全部測試腳本

    <test name = "allTestsInAClass" >
       <classes>
      <class name="whole.path.to.package.className />
       </classes>
    </test>

    選擇一個類中的部分測試腳本

    <test name = "aFewTestsFromAClass" >
       <classes>
      <class name="whole.path.to.package.className >
          <methods>
             <include name = "firstMethod" />
             <include name = "secondMethod" />
             <include name = "thirdMethod" />
          </methods>
      </class>
       </classes>
    </test>

    選擇一個包中的某些組

    <test name = "includedGroupsInAPackage" >
       <groups>
          <run>
             <include name = "includedGroup" />
          </run>
       </groups>
       <packages>
          <package name = "whole.path.to.package.* />
       </packages>
    </test>

    排除一個包中的某些組

    <test name = "excludedGroupsInAPackage" >
       <groups>
          <run>
             <exclude name = "excludedGroup" />
          </run>
       </groups>
       <packages>
          <package name = "whole.path.to.package.* />
       </packages>
    </test>

    其可以附帶的屬性有如下幾種,下面對各個屬性做單獨說明:

    (1)、name屬性

    此屬性屬于必須要有的,值可以自行設定,此名字會在testNG的報告中看到;

    (2)、verbose屬性

    此屬性為指定testNG報告的詳細程度,從0開始到10,其中10為最詳細,默認生成的xml此屬性值為1

    (3)、threadPoolSize屬性

    該屬性指定此test的線程池大小,為數(shù)字;

    @Test(threadPoolSize = 3, invocationCount = 10,  timeOut = 10000)
    public void testServer() {
    }

    (4)、invocationCount屬性

    該屬性指定此test的運行次數(shù),為數(shù)字,范例如上面的代碼所示;

    (5)、time-out屬性

    此屬性用于指定超時時間,該suite下所有的用例的超時時間,范例如上面的代碼所示;

    (6)、group-by-instances屬性

    此項用于那些有依賴的方法,且被依賴的對象有多個重載對象,因為如果是依賴方法,且該方法有多個重載方法,則默認是會將所有重載方法都跑完再運行被依賴方法,但有時候我們不想這樣,則將此項設置為true即可;

    <suite name="Factory" group-by-instances="true">

    (7)、preserve-order屬性

    值可輸入true或者false,如果為true,則用例執(zhí)行會按照在xml中的順序執(zhí)行,否則會亂序執(zhí)行,不添加此屬性的話默認是按順序執(zhí)行的;

    3、group標簽

    此標簽必然是在<test>標簽下的,用于標識那些組會被用于測試或者被排除在測試之外,其同級必然要包含一個<classes>標簽或者<pakages>標簽,用于指定groups來自于哪些包或者類;
    如下即為包含一個group,排除一個group的例子:

    <groups>
      <run>
         <include name = "includedGroupName" />
         <exclude name = "excludedGroupName" />
      </run>
    </groups>

    高級應用:

    <test name="Regression1">
      <groups>
        <define name="functest">
          <include name="windows"/>
          <include name="linux"/>
        </define>
      
        <define name="all">
          <include name="functest"/>
          <include name="checkintest"/>
        </define>
      
        <run>
          <include name="all"/>
        </run>
      </groups>
      
      <classes>
        <class name="test.sample.Test1"/>
      </classes>
    </test>

    4、其他

    其他的話就是測試腳本的選擇了,有三種方式:

    選擇一個包

    <packages>
        <package name = "packageName" />
    </packages>

    選擇一個類

    <classes>
        <class name = "className" />
    </classes>

    選擇一個方法

    <classes>
        <class name = "className" />
           <methods>
              <include name = "methodName" />
           </methods>
        </class>
    </classes>

    這里也支持正則表達式,例如:

    <test name="Test1">
      <classes>
        <class name="example1.Test1">
          <methods>
            <include name=".*enabledTestMethod.*"/>
            <exclude name=".*brokenTestMethod.*"/>
          </methods>
         </class>
      </classes>
    </test>

    十四、TestNG報告

    默認報告輸出位置為當前工程的test-output文件夾下,包括xml格式和html格式。
    如果想將報告輸出位置換個地方,則修改地方在如下圖所示位置:

    java中TestNG使用是怎樣的

    如果想要美化報告,則按照如下步驟:
    1、配置:Eclipse --> Window --> Preferences -->testng
    2、勾選Disable default listeners
    3、在Pre Defined Listeners 輸入框中輸入org.uncommons.reportng.HTMLReporter
    記得在POM上添加如下代碼:

    <dependency>
          <groupId>org.uncommons</groupId>
          <artifactId>reportng</artifactId>
          <version>1.1.4</version>
          <scope>test</scope>
          <exclusions>
            <exclusion>
              <groupId>org.testng</groupId>
              <artifactId>testng</artifactId>
            </exclusion>
          </exclusions>
         </dependency>
         <dependency>
           <groupId>com.google.inject</groupId>
           <artifactId>guice</artifactId>
           <version>3.0</version>
           <scope>test</scope>
         </dependency>

    不然無法運行的。
    如上圖所示,還可以自定義testng.xml的模板,并在上圖中指定。

    看完上述內(nèi)容,你們掌握java中TestNG使用是怎樣的的方法了嗎?如果還想學到更多技能或想了解更多相關內(nèi)容,歡迎關注億速云行業(yè)資訊頻道,感謝各位的閱讀!

    向AI問一下細節(jié)

    免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

    AI