selenium 数据驱动 (基于TestNG CSV)

来源:互联网 发布:python中syntax error 编辑:程序博客网 时间:2024/05/21 21:44

新建excel表  输入如下数据:

自动化测试selenium蝙蝠侠主演迈克尔超人导演圆谷英二生化危机编剧安德森

文件->另存为->保存类型为CSV文件,保存至D盘下,用记事本编辑, 另存为TestData.csv, 编码格式采用UTF-8

实现源码;

新建TestByCVS .java文件:

import java.io.BufferedReader;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.List;import org.testng.annotations.Test;import org.testng.annotations.DataProvider;import org.testng.annotations.BeforeMethod;import org.testng.annotations.AfterMethod;import java.util.concurrent.TimeUnit;import org.junit.Assert;import org.openqa.selenium.*;import org.openqa.selenium.firefox.*;public class TestByCVS {public static WebDriver driver;//定义当前方法中的返回对象作为测试脚本的测试数据集,命名为searchWords@DataProvider(name="TestData")public static Object[][] words() throws IOException{return getTestData("d:\\TestData.csv");  }@Test(dataProvider="TestData")public void testSearch(String words1, String words2, String result){   driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  driver.get("http://www.baidu.com");  driver.findElement(By.id("kw")).sendKeys(words1+ " "+words2);  driver.findElement(By.id("su")).click();  try {  Thread.sleep(10000);  } catch (InterruptedException e) {  e.printStackTrace();  }  Assert.assertTrue(driver.getPageSource().contains(result));  }@BeforeMethodpublic void BeforeMethod(){ driver =new FirefoxDriver();}@AfterMethodpublic void AfterMethod(){driver.quit();}public static Object[][] getTestData(String fileName) throws IOException{List <Object[]> records = new ArrayList<Object[]>();String record;BufferedReader file = new BufferedReader (new InputStreamReader(new FileInputStream(fileName),"UTF-8"));//忽略第一行file.readLine();//遍历 将内容存到records数组while((record=file.readLine())!=null){String fields[] = record.split(",");records.add(fields);}file.close();Object[][] results = new Object[records.size()][];for (int i=0; i<records.size();i++){results[i] = records.get(i);}return results;}//org.testng.TestNGException: //The data provider is trying to pass 1 parameters but the method TestByCVS#testSearch takes 3 and TestNG is unable in inject a suitable object }


(PS :编码运行过程中 出现最后注释的TestNG不能识别对象问题 ,是我CSV文件的问题。TestNG的日志不支持中文,更改eclipse.ini的语句后,火狐浏览器依旧乱码,Google浏览器则正常)


运行结束后Results of running class TestByCVS会出现中文乱码,在eclipse.ini加入如下语句

-Dfile.encoding=utf-8
-Dsun.jnu.encoding=utf-8
-Duser.language=en_US

 (Results of running class TestByCVS如下图所示)


(TestNG Report如下图所示:)



TestNG reports:






3 0