TestNg注解
package test; import org.testng.annotations.Optional; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class test01 { @Parameters({"name"})//声明参数 @Test public void test01(String name){ System.out.println("姓名是"+name); } @Parameters({"username","passwd"})//xml文件里面的内容需要与这里面的名称相对应 @Test public void test02(String user,String psw){ System.out.println("姓名是"+user+"密码是"+psw); } @Parameters({"database"})//Optional参数默认值 @Test public void test03(@Optional("mysql") String db){ System.out.println("数据库名称是"+db); } }
生成testng.xml文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> <suite name="All Test Suite"> <parameter name="name" value="yangyifan"></parameter> <parameter name="username" value="yangyifan"></parameter> <parameter name="passwd" value="123123"></parameter> <parameter name="database" value="yyfdatabase"></parameter> <test verbose="2" preserve-order="true" name="/Users/yangyifan/Documents/code/study/yyf/src/test/java/test/test01.java"> <classes> <class name="test.test01"> <methods> <include name="test01"></include> <include name="test02"/> <include name="test03"/> </methods> </class> </classes> </test> </suite>
DataProvider
在同一个类里面:
@DataProvider(name = "testdata") public Object[][] data(){ return new Object[][]{ {1,2,3}, {1,4,5}, {123,123,246} }; } @Test(dataProvider = "testdata")//与上方的@DataProvider参数保持一致 public void test04(int a,int b,int sum){ System.out.println(a+"+"+b+"="+sum); Assert.assertEquals((a+b),sum);//断言 }
@DataProvider public Object[][] data1(){ return new Object[][]{ {1,2,3}, {1,4,5}, {123,123,246} }; } @Test(dataProvider = "data1")//与方法名是一致 public void test05(int a,int b,int sum){ System.out.println(a+"+"+b+"="+sum);//及时上面数据集有问题也会全部执行 Assert.assertEquals((a+b),sum);//断言 }
在不同的类里面:
package test; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class DATA { @Test(dataProvider = "user",dataProviderClass = user.class) public void test(String name,String psw){ System.out.println("姓名是"+name+"密码是"+psw); } }
package test; import org.testng.annotations.DataProvider; public class user { @DataProvider public static Object[][] user(){ return new Object[][]{ {"YANGYIFAN","123123"}, {"YYF","123000"} }; } }
testng和csv数据驱动;