testNg使用

testNg使用

測試是檢查應(yīng)用程序的功能的過程是否按要求工作,在開發(fā)人員層面進(jìn)行單元測試,在采取適當(dāng)措施來測試每一個實(shí)體(類或方法)以確保最終產(chǎn)品符合要求。單元測試是非常必要的,這是軟件公司向他們的客戶提供高質(zhì)量的軟件產(chǎn)品必要前提。
JUnit讓開發(fā)人員了解測試的實(shí)用性,尤其是在單元測試這一模塊上比任何其他測試框架都要簡單明了。憑借一個相當(dāng)簡單,務(wù)實(shí),嚴(yán)謹(jǐn)?shù)募軜?gòu),JUnit已經(jīng)能夠“感染”了一大批開發(fā)人員。
JUnit缺點(diǎn):

  • 最初的設(shè)計(jì),使用于單元測試,現(xiàn)在只用于各種測試。
  • 不能依賴測試配置控制欠佳(安裝/拆卸)
  • 侵入性(強(qiáng)制擴(kuò)展類,并以某種方式命名方法)
  • 靜態(tài)編程模型(不必要的重新編譯)
  • 不適合管理復(fù)雜項(xiàng)目應(yīng)用,JUnit復(fù)雜項(xiàng)目中測試非常棘手。

TestNG是什么?TestNG按照官方的定義:
TestNG是一個測試框架,其靈感來自JUnit和NUnit,但引入了一些新的功能,使其功能更強(qiáng)大,使用更方便。
TestNG是一個開源自動化測試框架;TestNG表示下一代(Next Generation的首字母)。 TestNG類似于JUnit(特別是JUnit 4),但它不是JUnit框架的擴(kuò)展。它的靈感來源于JUnit。它的目的是優(yōu)于JUnit,尤其是在用于測試集成多類時。 TestNG的創(chuàng)始人是Cedric Beust(塞德里克·博伊斯特)。
TestNG消除了大部分的舊框架的限制,使開發(fā)人員能夠編寫更加靈活和強(qiáng)大的測試。 因?yàn)樗诤艽蟪潭壬辖梃b了Java注解(JDK5.0引入的)來定義測試,它也可以顯示如何使用這個新功能在真實(shí)的Java語言生產(chǎn)環(huán)境中。
TestNG的特點(diǎn)

  • 注解
  • TestNG使用Java和面向?qū)ο蟮墓δ?/li>
  • 支持綜合類測試(例如,默認(rèn)情況下,不用創(chuàng)建一個新的測試每個測試方法的類的實(shí)例)
  • 獨(dú)立的編譯時測試代碼和運(yùn)行時配置/數(shù)據(jù)信息
  • 靈活的運(yùn)行時配置
  • 主要介紹“測試組”。當(dāng)編譯測試,只要要求TestNG運(yùn)行所有的“前端”的測試,或“快”,“慢”,“數(shù)據(jù)庫”等
  • 支持依賴測試方法,并行測試,負(fù)載測試,局部故障
  • 靈活的插件API支持
  • 多線程測試
  1. 引用pom依賴
  <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.8.7</version>
            <scope>test</scope>
  </dependency>
  1. 注解:在TestNG中,我們可以使用以下注釋來執(zhí)行測試類的配置,如設(shè)置/清理數(shù)據(jù)庫,準(zhǔn)備虛擬數(shù)據(jù),部署/關(guān)閉服務(wù)器等。
@BeforeSuite - 對于套件測試,在此套件中的所有測試運(yùn)行之前運(yùn)行。
@AfterSuite - 對于套件測試,在此套件中的所有測試運(yùn)行之后運(yùn)行。
@BeforeTest - 對于套件測試,在運(yùn)行屬于<test>標(biāo)簽內(nèi)的類的任何測試方法之前運(yùn)行。
@AfterTest - 對于套件測試,在運(yùn)行屬于<test>標(biāo)簽內(nèi)的類的所有測試方法都已運(yùn)行之后運(yùn)行。
@BeforeGroups: 在調(diào)用屬于該組的第一個測試方法之前運(yùn)行。
@AfterGroups: 在調(diào)用屬于組的最后一個測試方法之后運(yùn)行。
@BeforeClass- 在當(dāng)前類的第一個測試方法之前運(yùn)行。
@AfterClass 運(yùn)行當(dāng)前類中的所有測試方法之后都運(yùn)行。
@BeforeMethod - 在每個測試方法之前運(yùn)行。
@AfterMethod - 在每個測試方法之后運(yùn)行。

注:套件測試是一起運(yùn)行的多個測試類
3.異常,可通過expectedExceptions捕獲

@Test(expectedExceptions = UserLoginException.class)
    public void throwIfLgoinFailedl() throws UserLoginException {
        orderBo.login(null,null);
    }

4.@Test(enabled = false)有助于禁用此測試用例

  1. “超時”表示如果單元測試花費(fèi)的時間超過指定的毫秒數(shù),那么TestNG將會中止它并將其標(biāo)記為失敗。
@Test(timeOut = 4500) // time in mulliseconds
    public void testThisShouldPass() throws InterruptedException {
        Thread.sleep(4000);
    }
  1. 分組測試是TestNG中的一個新的創(chuàng)新功能,它在JUnit框架中是不存在的。 它允許您將方法調(diào)度到適當(dāng)?shù)牟糠?,并?zhí)行復(fù)雜的測試方法分組。 您不僅可以聲明屬于某個分組的方法,還可以指定包含其他組的組。 然后調(diào)用TestNG,并要求其包含一組特定的組(或正則表達(dá)式),同時排除另一個分組。 組測試提供了如何分區(qū)測試的最大靈活性,如果您想要背靠背運(yùn)行兩組不同的測試,則不需要重新編譯任何內(nèi)容。
    使用<groups>標(biāo)記在testng.xml文件中指定分組。 它可以在<test>或<suite>標(biāo)簽下找到。 <suite>標(biāo)簽中指定分組適用于其下的所有<test>標(biāo)簽。

runSelenium()和runSelenium1()屬于分組:selenium-test。testConnectOracle()和testConnectMsSQL()屬于分組:database 。如果分組selenium-test和database通過,則runFinal()將被執(zhí)行。

public class TestGroup {

    @BeforeGroups("database")
    public void setupDB() {
        System.out.println("setupDB()");
    }

    @AfterGroups("database")
    public void cleanDB() {
        System.out.println("cleanDB()");
    }

    @Test(groups = "selenium-test")
    public void runSelenium() {
        System.out.println("runSelenium()");
    }

    @Test(groups = "selenium-test")
    public void runSelenium1() {
        System.out.println("runSelenium()1");
    }

    @Test(groups = "database")
    public void testConnectOracle() {
        System.out.println("testConnectOracle()");
    }

    @Test(groups = "database")
    public void testConnectMsSQL() {
        System.out.println("testConnectMsSQL");
    }

    @Test(dependsOnGroups = { "database", "selenium-test" })
    public void runFinal() {
        System.out.println("runFinal");
    }
}
  • 測試套件是用于測試軟件程序的行為或一組行為的測試用例的集合。 在TestNG中,我們無法在測試源代碼中定義一個套件,但它可以由一個XML文件表示,因?yàn)樘准菆?zhí)行的功能。 它還允許靈活配置要運(yùn)行的測試。 套件可以包含一個或多個測試,并由<suite>標(biāo)記定義。
    <suite>是testng.xml的根標(biāo)記。 它描述了一個測試套件,它又由幾個<test>部分組成。
    下表列出了<suite>接受的所有定義的合法屬性。
屬性 描述
name 套件的名稱,這是一個強(qiáng)制屬性。
verbose 運(yùn)行的級別或詳細(xì)程度。
parallel TestNG是否運(yùn)行不同的線程來運(yùn)行這個套件。
thread-count 如果啟用并行模式(忽略其他方式),則要使用的線程數(shù)。
annotations 在測試中使用的注釋類型。
time-out 在本測試中的所有測試方法上使用的默認(rèn)超時。
  • 指定包名稱而不是類名稱
<suite name="TestAll">

    <test name="order">
        <packages>
            <package name="com.test.*" />
        </packages>
    </test>

</suite>
  • 指定包含或排除的方法
<?xml version="1.0" encoding="UTF-8"?>
<suite name="TestAll">

  <test name="order">
    <classes>
        <class name="com.test.TestConfig" />
        <class name="com.test.TestOrder">
            <methods>
                <include name="testMakeOrder" />
                <include name="testUpdateOrder" />
                <!--
                    <exclude name="testMakeOrder" />
                 -->
            </methods>
        </class>
    </classes>
  </test>

</suite>
  • include、exclude指定要包括或排除某個分組
<?xml version="1.0" encoding="UTF-8"?>
<suite name="TestAll">

  <test name="database">
    <groups>
        <run>
            <exclude name="brokenTests" />
            <include name="db" />
        </run>
    </groups>

    <classes>
        <class name="com.test.TestDatabase" />
    </classes>
  </test>

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

  • 在@Test注釋中使用屬性dependsOnMethods,或者

  • 在@Test注釋中使用屬性dependsOnGroups。

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

  • 使用testng.xml

  • 使用數(shù)據(jù)提供者(@Parameters或@DataProvider將參數(shù)傳遞給@Test方法)

  • @Parameters

<?xml version="1.0" encoding="UTF-8"?>
<suite name="test-parameter">

    <test name="example1">

        <parameter name="dbconfig" value="db.properties" />
        <parameter name="poolsize" value="10" />

        <classes>
            <class name="com.test.TestParameterXML" />
        </classes>

    </test>

</suite>
  • @DataProvider
public class TestParameterDataProvider {

    @Test(dataProvider = "provideNumbers")
    public void test(int number, int expected) {
        Assert.assertEquals(number + 10, expected);
    }

    @DataProvider(name = "provideNumbers")
    public Object[][] provideData() {

        return new Object[][] { { 10, 20 }, { 100, 110 }, { 200, 210 } };
    }

}
  • @DataProvider支持傳遞一個對象參數(shù)
public class TestParameterDataProvider2 {

    @Test(dataProvider = "dbconfig")
    public void testConnection(Map<String, String> map) {

        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println("[Key] : " + entry.getKey() + " [Value] : " + entry.getValue());
        }

    }

    @DataProvider(name = "dbconfig")
    public Object[][] provideDbConfig() {
        Map<String, String> map = readDbConfig();
        return new Object[][] { { map } };
    }

    public Map<String, String> readDbConfig() {

        Properties prop = new Properties();
        InputStream input = null;
        Map<String, String> map = new HashMap<String, String>();

        try {
            input = getClass().getClassLoader().getResourceAsStream("db.properties");

            prop.load(input);

            map.put("jdbc.driver", prop.getProperty("jdbc.driver"));
            map.put("jdbc.url", prop.getProperty("jdbc.url"));
            map.put("jdbc.username", prop.getProperty("jdbc.username"));
            map.put("jdbc.password", prop.getProperty("jdbc.password"));

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return map;

    }

}
  • @DataProvider + 方法,根據(jù)測試方法名稱傳遞不同的參數(shù)
public class TestParameterDataProvider3 {

    @Test(dataProvider = "dataProvider")
    public void test1(int number, int expected) {
        Assert.assertEquals(number, expected);
    }

    @Test(dataProvider = "dataProvider")
    public void test2(String email, String expected) {
        Assert.assertEquals(email, expected);
    }

    @DataProvider(name = "dataProvider")
    public Object[][] provideData(Method method) {

        Object[][] result = null;

        if (method.getName().equals("test1")) {
            result = new Object[][] {
                { 1, 1 }, { 200, 200 }
            };
        } else if (method.getName().equals("test2")) {
            result = new Object[][] {
                { "test@gmail.com", "test@gmail.com" },
                { "test@yahoo.com", "test@yahoo.com" }
            };
        }

        return result;

    }

}
  • 在TestNG中,我們可以使用org.testng.ITestContext來確定調(diào)用當(dāng)前測試方法的運(yùn)行時參數(shù)。 在最后一個例子中,根據(jù)包含的分組名稱傳遞參數(shù)
public class TestParameterDataProvider4 {

    @Test(dataProvider = "dataProvider", groups = {"groupA"})
    public void test1(int number) {
        Assert.assertEquals(number, 1);
    }

    @Test(dataProvider = "dataProvider", groups = "groupB")
    public void test2(int number) {
        Assert.assertEquals(number, 2);
    }

    @DataProvider(name = "dataProvider")
    public Object[][] provideData(ITestContext context) {

        Object[][] result = null;

        //get test name
        //System.out.println(context.getName());

        for (String group : context.getIncludedGroups()) {

            System.out.println("group : " + group);

            if ("groupA".equals(group)) {
                result = new Object[][] { { 1 } };
                break;
            }

        }

        if (result == null) {
            result = new Object[][] { { 2 } };
        }
        return result;

    }

}
  • xml
<?xml version="1.0" encoding="UTF-8"?>
<suite name="test-parameter">

    <test name="example1">

        <groups>
            <run>
                <include name="groupA" />
            </run>
        </groups>

        <classes>
            <class name="com.test.TestParameterDataProvider4" />
        </classes>

    </test>

</suite>
  • invocationCount確定TestNG應(yīng)該運(yùn)行這個測試方法的次數(shù)

  • threadPoolSize屬性告訴TestNG創(chuàng)建一個線程池以通過多個線程運(yùn)行測試方法。 使用線程池,會大大降低測試方法的運(yùn)行時間。

  • TestNG + Spring

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd
    ">

    <context:component-scan base-package="com.test" />

</beans>
#代碼
@Test
@ContextConfiguration(locations = { "classpath:spring-test-config.xml" })
public class TestSpring extends AbstractTestNGSpringContextTests {

    @Autowired
    EmailGenerator emailGenerator;

    @Test()
    void testEmailGenerator() {

        String email = emailGenerator.generate();
        System.out.println(email);

        Assert.assertNotNull(email);
        Assert.assertEquals(email, "feedback@test.com");


    }

}
  • JUnit 4和TestNG都是Java中非常受歡迎的單元測試框架。兩種框架在功能上看起來非常相似。 哪一個更好? 在Java項(xiàng)目中應(yīng)該使用哪個單元測試框架?
    下面表中概括了JUnit 4和TestNG之間的功能比較。如下圖所示 -
    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機(jī)制,建議將圖片保存下來直接上傳(img-p7lU2vxB-1597108812642)(evernotecid://1B6E6F67-D7E8-416E-8DE9-096BB4A77F37/appyinxiangcom/10870897/ENResource/p492)]
  1. 注釋支持
    注釋/注解支持在JUnit 4和TestNG中是非常類似的。
特點(diǎn) JUnit 4TestNG
測試注釋 @Test @Test
在套件中的所有測試運(yùn)行之前運(yùn)行 - @BeforeSuite
在套件中的所有測試運(yùn)行之后運(yùn)行 - @AfterSuite
測試之前運(yùn)行 - @BeforeTest
測試之后運(yùn)行 - @AfterTest
在調(diào)用屬于任何這些組的第一個測試方法之前運(yùn)行 - @BeforeGroups
在調(diào)用屬于任何這些組的第一個測試方法之后運(yùn)行 - @AfterGroups
在調(diào)用當(dāng)前類的第一個測試方法之前運(yùn)行 @BeforeClass @BeforeClass
在調(diào)用當(dāng)前類的第一個測試方法之后運(yùn)行 @AfterClass @AfterClass
在每個測試方法之前運(yùn)行 @Before @BeforeMethod
在每個測試方法之后運(yùn)行 @After @AfterMethod
忽略測試 @ignore @Test(enbale=false)
預(yù)期的異常 @Test(expected = ArithmeticException.class) @Test(expectedExceptions = ArithmeticException.class)
超時測試 @Test(timeout = 1000) @Test(timeout = 1000)
  • JUnit4和TestNG之間的主要注釋差異是:
    在JUnit 4中,我們必須聲明“@BeforeClass”和“@AfterClass”方法作為靜態(tài)方法。 TestNG在方法聲明中更靈活,它沒有這個約束。
    3個額外的setUp / tearDown級別:suite和group(@Before / AfterSuite,@Before / After Test,@Before / After Group)。
  • JUnit 4
@BeforeClass
public static void oneTimeSetUp() {
    // one-time initialization code
    System.out.println("@BeforeClass - oneTimeSetUp");
}
  • JavaTestNG
@BeforeClass
public void oneTimeSetUp() {
        // one-time initialization code
        System.out.println("@BeforeClass - oneTimeSetUp");
}

Java在JUnit 4中,注釋命名約定有點(diǎn)混亂,例如“Before”,“After”和“Expected”,我們并不真正了解“Before”和“After”之前的內(nèi)容,以及要測試中的“預(yù)期” 方法。TestiNG更容易理解,它使用類似“BeforeMethod”,“AfterMethod”和“ExpectedException”就很明了。

  1. 異常測試
    “異常測試”是指從單元測試中拋出的異常,此功能在JUnit 4和TestNG中都可實(shí)現(xiàn)。
  • JUnit 4
@Test(expected = ArithmeticException.class)
public void divisionWithException() {
  int i = 1/0;
}
  • TestNG
@Test(expectedExceptions = ArithmeticException.class)
public void divisionWithException() {
  int i = 1/0;
}
  1. 忽略測試
    “忽略”表示是否應(yīng)該忽略單元測試,該功能在JUnit 4和TestNG中均可實(shí)現(xiàn)。
  • JUnit 4
@Ignore("Not Ready to Run")
@Test
public void divisionWithException() {
  System.out.println("Method is not ready yet");
}
  • TestNG
@Test(enabled=false)
public void divisionWithException() {
  System.out.println("Method is not ready yet");
}
  1. 時間測試
    “時間測試”表示如果單元測試所花費(fèi)的時間超過指定的毫秒數(shù),則測試將會終止,并將其標(biāo)記為失敗,此功能在JUnit 4和TestNG中均可實(shí)現(xiàn)。
  • JUnit 4
@Test(timeout = 1000)
public void infinity() {
    while (true);
}
  • TestNG
@Test(timeOut = 1000)
public void infinity() {
    while (true);
}
  1. 套件測試
    “套件測試”是指捆綁幾個單元測試并一起運(yùn)行。 此功能在JUnit 4和TestNG中都可實(shí)現(xiàn)。 然而,兩者都使用非常不同的方法來實(shí)現(xiàn)它。
    JUnit 4“@RunWith”和“@Suite”用于運(yùn)行套件測試。下面的類代碼表示在JunitTest5執(zhí)行之后,單元測試“JunitTest1”和“JunitTest2”一起運(yùn)行。 所有的聲明都是在類內(nèi)定義的。
@RunWith(Suite.class)
@Suite.SuiteClasses({
        JunitTest1.class,
        JunitTest2.class
})
public class JunitTest5 {
}
  • TestNGXML文件用于運(yùn)行套件測試。以下XML文件表示單元測試“TestNGTest1”和“TestNGTest2”將一起運(yùn)行。
suite name="My test suite">
  <test name="testing">
    <classes>
       <class name="com.fsecure.demo.testng.TestNGTest1" />
       <class name="com.fsecure.demo.testng.TestNGTest2" />
    </classes>
  </test>
</suite>

XMLTestNG可以做捆綁類測試,也可以捆綁方法測試。 憑借TestNG獨(dú)特的“分組”概念,每種方法都可以與一個組合相結(jié)合,可以根據(jù)功能對測試進(jìn)行分類(分組)。 例如,
下面是一個有四個方法的類,三個組(method1,method2和method3)

@Test(groups="method1")
public void testingMethod1() {
  System.out.println("Method - testingMethod1()");
}

@Test(groups="method2")
public void testingMethod2() {
    System.out.println("Method - testingMethod2()");
}

@Test(groups="method1")
public void testingMethod1_1() {
    System.out.println("Method - testingMethod1_1()");
}

@Test(groups="method4")
public void testingMethod4() {
    System.out.println("Method - testingMethod4()");
}

使用以下XML文件,可以僅使用組“method1”執(zhí)行單元測試。

<suite name="My test suite">
  <test name="testing">
      <groups>
      <run>
        <include name="method1"/>
      </run>
    </groups>
    <classes>
       <class name="com.fsecure.demo.testng.TestNGTest5_2_0" />
    </classes>
  </test>
</suite>
XML通過“分組”測試概念,集成測試的可能性是無限制的。 例如,我們只能從所有單元測試類中測試“DatabaseFuntion”分組。
  1. 參數(shù)化測試
    “參數(shù)化測試”是指單位測試參數(shù)值的變化。 此功能在JUnit 4和TestNG中都實(shí)現(xiàn)。 然而,兩者都使用非常不同的方法來實(shí)現(xiàn)它。
    JUnit 4“@RunWith”和“@Parameter”用于提供單元測試的參數(shù)值,@Parameters必須返回List [],參數(shù)將作為參數(shù)傳入類構(gòu)造函數(shù)。
@RunWith(value = Parameterized.class)
public class JunitTest6 {

     private int number;

     public JunitTest6(int number) {
        this.number = number;
     }

     @Parameters
     public static Collection&lt;Object[]]]> data() {
       Object[][] data = new Object[][] { { 1 }, { 2 }, { 3 }, { 4 } };
       return Arrays.asList(data);
     }

     @Test
     public void pushTest() {
       System.out.println("Parameterized Number is : " + number);
     }
}

這里有很多限制,我們必須遵循“JUnit”的方式來聲明參數(shù),并且必須將參數(shù)傳遞給構(gòu)造函數(shù)才能初始化類成員作為測試的參數(shù)值。參數(shù)類的返回類型為“List []”,數(shù)據(jù)已被限制為String或用于測試的原始類型值。
TestNGXML文件或“@DataProvider”用于提供不同參數(shù)進(jìn)行測試。
用于參數(shù)化測試的XML文件 -
只有“@Parameters”在需要參數(shù)測試的方法中聲明,參數(shù)化數(shù)據(jù)將在TestNG的XML配置文件中提供。 通過這樣做,我們可以使用不同數(shù)據(jù)集的單個測試用例,甚至獲得不同的結(jié)果。 另外,即使是最終用戶,QA還是QE都可以在XML文件中提供自己的數(shù)據(jù)進(jìn)行測試。

public class TestNGTest6_1_0 {

@Test
@Parameters(value="number")
public void parameterIntTest(int number) {
       System.out.println("Parameterized Number is : " + number);
    }
}

JavaXML文件的內(nèi)容如下

<suite name="My test suite"]]>
  <test name="testing"]]>

    <parameter name="number" value="2"/&gt;

    <classes>
       <class name="com.fsecure.demo.testng.TestNGTest6_0" />
   </classes>
  </test>
  </suite>

XML@DataProvider用于參數(shù)化測試將數(shù)據(jù)值拉入XML文件可能非常方便,但測試偶爾會需要復(fù)雜的類型,這些類型不能被表示為一個字符串或一個原始類型值。 TestNG使用@DataProvider注解來處理這種情況,這有助于將復(fù)雜參數(shù)類型映射到測試方法。
@DataProvider for Vector,String或Integer作為參數(shù),參考如下代碼 -

@Test(dataProvider = "Data-Provider-Function")
    public void parameterIntTest(Class clzz, String[] number) {
       System.out.println("Parameterized Number is : " + number[0]);
       System.out.println("Parameterized Number is : " + number[1]);
    }

    //This function will provide the patameter data
    @DataProvider(name = "Data-Provider-Function")
    public Object[][] parameterIntTestProvider() {
        return new Object[][]{
                   {Vector.class, new String[] {"java.util.AbstractList",
"java.util.AbstractCollection"}},
                   {String.class, new String[] {"1", "2"}},
                   {Integer.class, new String[] {"1", "2"}}
                  };
    }

Java@DataProvider作為對象的參數(shù)“TestNGTest6_3_0”是一個簡單的對象,只需使用get/set方法進(jìn)行演示。

@Test(dataProvider = "Data-Provider-Function")
public void parameterIntTest(TestNGTest6_3_0 clzz) {
   System.out.println("Parameterized Number is : " + clzz.getMsg());
   System.out.println("Parameterized Number is : " + clzz.getNumber());
}

//This function will provide the patameter data
@DataProvider(name = "Data-Provider-Function")
public Object[][] parameterIntTestProvider() {

    TestNGTest6_3_0 obj = new TestNGTest6_3_0();
    obj.setMsg("Hello");
    obj.setNumber(123);

    return new Object[][]{
               {obj}
    };
}

JavaTestNG的參數(shù)化測試非常用戶友好和靈活(在XML文件或類內(nèi))。 它可以支持許多復(fù)雜的數(shù)據(jù)類型作為參數(shù)值,可能性是無限的。 如上例所示,我們甚至可以傳入我們自己的對象(TestNGTest6_3_0)進(jìn)行參數(shù)化測試

7.依賴性測試
“參數(shù)化測試”表示方法是依賴性測試,它將在所需方法之前執(zhí)行。 如果依賴方法失敗,則所有后續(xù)測試將會被跳過,不會被標(biāo)記為失敗。
JUnit 4JUnit框架著重于測試隔離; 目前它不支持此功能。
TestNG它使用“dependOnMethods”來實(shí)現(xiàn)依賴測試如下

@Test
public void method1() {
   System.out.println("This is method 1");
}

@Test(dependsOnMethods={"method1"})
public void method2() {
    System.out.println("This is method 2");
}

Java“method2()”只有在“method1()”運(yùn)行成功的情況下才會執(zhí)行,否則“method2()”將跳過測試。
結(jié)論
在考慮所有功能比較之后,建議使用TestNG作為Java項(xiàng)目的核心單元測試框架,因?yàn)門estNG在參數(shù)化測試,依賴測試和套件測試(分組概念)方面更加突出。 TestNG用于高級測試和復(fù)雜集成測試。 它的靈活性對于大型測試套件尤其有用。 此外,TestNG還涵蓋了整個核心的JUnit4功能。這樣說來,好像也沒有理由使用JUnit了

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容