相对于junit4来说testNG框架会出具更多的常用注解;详细的测试报告;
第一步:下载testng;help_install new software_add (name=TestNG location=http//beust.com/eclipse/) _OK_next_finish_OK-yes 安装完成重启eclipse
第二步:新建java工程,命名为“TestNGProj”,配置好运行Webdriver的相关jar文件;
第三步:单击选中新建工程的名称,按下Ctrl+N组合键,在弹出的对话框中选择“TestNG”下的“TestNGclass”选项,单击“Next”按钮;输入Source Packagename Classname;finish
第四步:编写webdriver测试代码如下 *运行之前要将代码拖拽到Src目录下
package cn.china; import org.openqa.selenium.*; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; import org.testng.annotations.BeforeMethod; import org.testng.annotations.AfterMethod; public class FirstTestNGDemo { public WebDriver driver; String baseUrl="http://www.sogou.com/"; @Test public void testsearch() { driver.get(baseUrl+"/"); driver.findElement(By.id("query")).sendKeys("光荣之路自动化测试"); driver.findElement(By.id("stb")).click(); } @BeforeMethod public void beforeMethod() { System.setProperty("webdriver.gecko.driver", "C:\\Program Files (x86)\\Mozilla Firefox\\geckodriver.exe"); driver=new FirefoxDriver(); } @AfterMethod public void afterMethod() { //driver.quit(); } }
运行结束后可以到工程目录下test-output下找到index.html或者emailable-report.html查看测试报告;
第五步:创建“Annotation”java类,代码如下
package cn.china; import org.testng.annotations.Test; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.BeforeTest; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterSuite; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeClass; public class Annotation { @Test public void f() { System.out.println("测试用例1被调用"); } @Test public void s(){ System.out.println("测试用例2被调用"); } @BeforeMethod public void beforeMethod() { System.out.println("在每个方法运行之前执行"); } @AfterMethod public void afterMethod() { System.out.println("在每个方法运行之后执行"); } @BeforeClass public void beforeclass(){ System.out.println("在当前测试类的第一个测试方法开始调用前执行"); } @AfterClass public void afterClass(){ System.out.println("在当前类的最后一个测试方法运行结束后执行"); } @BeforeTest public void befoerclass(){ System.out.println("在测试方法test开始运行之前执行"); } @AfterTest public void afterclass(){ System.out.println("在测试方法Test开始运行后执行"); } @BeforeSuite public void beforeSuite(){ System.out.println("在当前测试集合suite中的所有程序开始之前执行"); } @AfterSuite public void afterSuite(){ System.out.println("在当前测试集合suite中的所有程序运行结束后执行"); } }
第六步:测试集合testsuite new-file-testng(filename=tesng.xml);在testng.xml文档中选择source栏进行编辑,代码如下:在eclipse里 运行testng.xml 发现2个测试用例都被运行,实现批量执行测试用例;
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> <suite name="TestNGSuite"> <test name ="test1"> <classes> <class name="cn.china.FirstTestNGDemo"/> <class name="cn.china.Annotation"/> </classes> </test> </suite>