欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

testNG学习之参数化

程序员文章站 2022-05-31 23:27:52
...
        TestNG的测试方法中可以传入参数,而参数的来源有两种方法:xml中设置和自定义方法生成,下面给出例子。
1、tesgng.xml中设置
<code="java">
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="zhanglutest" verbose="2" parallel="tests" thread-count="2">
    <test name="testcase1">
    <parameter name="name" value="zhanglu"></parameter>
    <parameter name="age" value="22"></parameter>
    <classes>
    <class name="com.propertiesfile.WaybillSelect"></class>
        </classes>
    </test>
</suite>
       测试方法中调用:
package com.propertiesfile;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class WaybillSelect {
@Test
@Parameters({"name","age"})
public void test2(String name,int age) {
System.out.println("name is:"+name+",age is:"+age);
}
}
</code>
2、通过DataProvider自定义
      下面的代码演示了一个参数和多个参数的情况,以及参数类与测试方法不在同一个类中的调用。
<code="java">
参数生成类:
package com.classes.test;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class ClassTest {
  @DataProvider(name="twoParam")
  public Object[][] paramTwo(){
  Object[][] aa = new Object[][] {
  {"zhangsan",22},
  {"lisi",25},
  {"wangwu",30}
  };
  return aa;
  }
  @DataProvider(name="fourParam")
  public Object[][] paramFour(){
  Object[][] aa = new Object[][] {
  {"zhangsan",20,"china",160},
  {"lisi",25,"english",180}
  };
  return aa;
  }
}
测试方法类:
package com.moneyselect;
import com.classes.test.ClassTest;
import org.testng.annotations.*;

public class MoneySelectTest {
@Test(dataProvider="oneParam")
public void test1(int money) {
System.out.println("I have "+money+" yuan");
}

@DataProvider(name="oneParam")
public Object[] providermethod() {
Object[] a = new Object[]{100,20,30};
return a;
}

        @Test(dataProvider="twoParam",dataProviderClass=ClassTest.class)
public void test2(String name,int age) {
         System.out.println("My name is:"+name+",i am "+age+" years old");
}

@Test(dataProvider="fourParam",dataProviderClass=ClassTest.class)
public void test3(String name,int age,String national,int weight) {
System.out.println("My name is "+name+",i am "+age+" years old,i come from "+national+",my weight is "+weight+" cm");
}
}
testng.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="zhanglutest" verbose="2" parallel="tests" thread-count="2">
    <test name="testcase1">
    <classes>
    <class name="com.moneyselect.MoneySelectTest"></class>
        </classes>
    </test>
</suite>
</code>
      运行结果如下:
I have 100 yuan
I have 20 yuan
I have 30 yuan
My name is:zhangsan,i am 22 years old
My name is:lisi,i am 25 years old
My name is:wangwu,i am 30 years old
My name is zhangsan,i am 20 years old,i come from china,my weight is 160 cm
My name is lisi,i am 25 years old,i come from english,my weight is 180 cm
相关标签: testng 参数化