TestNG learning - the use of parameters

 Test methods can also take advantage of some parameters. Any number of parameters can be used on each test method and TestNG is instructed to pass the correct parameters using the @Parameters annotation.

        There are two ways to set these parameters: using testng.xml or programmatically.

1. Use testng.xml 

        If the parameters are relatively simple values, they can be specified in testng.xml:

@Parameters({ "first-name" })@Testpublic void testSingleString(String firstName) {
   
     System.out.println("Invoked testString " + firstName);  assert "Cedric".equals(firstName);}

        In the above code, we specified that the parameter firstName of the Java method should receive the value of the XML parameter called first-name. XML parameters are defined in testng.xml:​​​​​​​​

<suite name="My suite">  <parameter name="first-name"  value="Cedric"/>  <test name="Simple example">  <-- ... -->

        It can also be used in @Before/After and @Factory annotations:​​​​​​​​

@Parameters({ "datasource", "jdbcDriver" })@BeforeMethodpublic void beforeTest(String ds, String driver) {
   
     m_dataSource = ...;      // 具体datasource的值  m_jdbcDriver = driver;}

        In the above code, the two Java parameters ds and driver will receive the values ​​assigned to the attributes datasource and jdbc-driver respectively.

        You can also use the Optional annotation to declare parameters as optional, which is equivalent to setting a default value:​​​​​​​​

@Parameters("db")@Testpublic void testNonExistentParameter(@Optional("mysql") String db) { ... }

        If no parameter named "db" is found in the testng.xml file, the test method will receive the default value specified inside the @Optional annotation: "mysql".

        Where the @Parameters annotation can be placed:

  • On methods annotated with @Before/After and @Factory.

  • Can be used in at most one constructor of a test class. In this case, whenever a test class needs to be instantiated, TestNG will call this particular constructor with parameters initialized to the values ​​specified in testng.xml. This feature can be used to initialize fields in a class to values ​​that will be used by test methods.

    • Note:

      • XML parameters are mapped to Java parameters in the same order as they are found in the annotation, and TestNG will issue an error if the numbers do not match.

      • Parameters are scoped. In testng.xml, they can be declared under the <suite> tag or under <test>. If two parameters have the same name, the priority defined in <test> is chosen. This is handy if you need to specify a parameter that applies to all tests and only override its value for some tests.

2. Use the parameters of DataProviders

        If you need to pass complex parameters or you need parameters created from Java (complex objects, objects read from properties files or databases, etc.), specifying parameters in testng.xml may not be enough. In this case, a data provider can be used to provide the values ​​that need to be tested. A data provider is a method on a class that returns an array of arrays of objects. This method is annotated with @DataProvider:​​​​​​​​

//This method will provide data to any test method that declares that its Data Provider//is named "test1"@DataProvider(name = "test1")public Object[][] createData1() {
   
    return new Object[][] {
   
      { "Cedric", new Integer(36) },   { "Anne", new Integer(37)}, };} //This test method declares that its data should be supplied by the Data Provider//named "test1"@Test(dataProvider = "test1")public void verifyData1(String n1, Integer n2) {
   
    System.out.println(n1 + " " + n2);}

Output result:​​​​​​​​

Cedric 36Anne 37

        A @Test method specifies its data provider using the dataProvider attribute. The name must correspond to a method on the same class annotated with @DataProvider(name="...") with a matching name.

        By default, data providers will be looked up in the current test class or one of its base classes. If you want to put the data provider in a different class, it must be a static method or a class with a no-arg constructor, and specify the class where it can be found in the dataProviderClass attribute:​​​​​​​​

public class StaticProvider {
   
     @DataProvider(name = "create")  public static Object[][] createData() {
   
       return new Object[][] {
   
         new Object[] { new Integer(42) }    };  }} public class MyTest {
   
     @Test(dataProvider = "create", dataProviderClass = StaticProvider.class)  public void test(Integer n) {
   
       // ...  }}

        Data providers also support injection . TestNG will use the test context for injection. Data provider methods can return one of the following types:

  • An array of object arrays (Object[][]) where the size of the first dimension is the number of times the test method will be invoked and the size of the second dimension contains the array methods of objects that must be compatible with the argument types of the test. Code as shown above.

  • Iterator<Object[]>. The only difference from Object[][] is that iterators allow you to create test data lazily. TestNG will in turn call the iterator and then call the test method with the parameters returned by the iterator. This is especially useful if you have many parameter sets to pass to the method and you don't want to create all of them up front.

    • Array of Objects (Object[]). This is similar to Iterator<Object[]>, and the test method is called once for each element of the source array.

    • Iterator<Object>. Lazy alternative to Object[]. The test method is called once for each element of the iterator.

        The return type is not limited to Object, MyCustomData[][] or Iterator <Supplier> are also possible. The only restriction is that, in the case of iterators, the parameter types themselves cannot be explicitly parameterized. The following example:​​​​​​​​

@DataProvider(name = "test1")public Iterator<Object[]> createData() {
   
     return new MyIterator(DATA);}

    Use MyCustomData[] as the return value:​​​​​​​​

@DataProvider(name = "test1")public MyCustomData[] createData() {
   
     return new MyCustomData[]{ new MyCustomData() };}

    Or its lazy option of Iterator<MyCustomData>:​​​​​​​​

@DataProvider(name = "test1")public Iterator<MyCustomData> createData() {
   
     return Arrays.asList(new MyCustomData()).iterator();}

     Unable to explicitly parameterize the parameter type (Stream) of Iterator:​​​​​​​​

@DataProvider(name = "test1")public Iterator<Stream> createData() {
   
     return Arrays.asList(Stream.of("a", "b", "c")).iterator();}

    If you declare @DataProvider with a java.lang.reflect.Method as the first parameter, TestNG will pass the current test method as the first parameter. This feature is especially useful when several test methods use the same @DataProvider and you want it to return different values ​​depending on which test method provides data to it.

    For example, the following code prints the name of the test method in its @DataProvider:​​​​​​​​

@DataProvider(name = "dp")public Object[][] createData(Method m) {
   
     System.out.println(m.getName());  // print test method name  return new Object[][] { new Object[] { "Cedric" }};} @Test(dataProvider = "dp")public void test1(String s) {
   
   } @Test(dataProvider = "dp")public void test2(String s) {
   
   }

        Result:​​​​​​

test1test2

        @DataProvider can also specify how to run in parallel:

@DataProvider(parallel = true)

        Parallel data providers run from XML files share the same thread pool, which by default has a size of 10. This value can be modified in the <suite> tag of the XML file:

<suite name="Suite1" data-provider-thread-count="20" >

If you want to run some specific data providers in other thread pools, you need to run them from other XML files.

3. Parameters in the test report

    It is possible to embed the parameter call into the test report to use, here is a simple example:

picture

Welcome to pay attention to my public account [Test Memo] to share and exchange together~

おすすめ

転載: blog.csdn.net/hashsabr/article/details/113828542