使用TestNG 和 CSV文件进行数据驱动
package testNGPractice; 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.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import cn.gloryroad.Log; import scr.comm.OpenBrowserInfo; public class TestDataDriverByCSVFile { public WebDriver driver; private String url = "http://www.sogou.com/"; // 使用注解 DataProvider ,,将数据结合命名为“TestData” @DataProvider(name = "testData") public static Object[][] words() throws IOException { // 调用类中的静态方法 getTestData,获取CSV文件的测试数据; return getTestData("D:\\dataTest.csv"); } @Test(dataProvider = "testData") public void TestSearch(String serachWord1, String searchWord2, String searchResult) { Log.startTextCase("TestSearch" + serachWord1 + " " + searchWord2 + " " + searchResult); // 打开搜狗首页; driver.get(url); // 使用CSV文件中每个数据行的前俩个词汇作为搜索词! // 在搜索词中间增加一个空格; driver.findElement(By.id("query")).sendKeys(serachWord1 + "" + searchWord2); // 单击搜索按钮; driver.findElement(By.id("stb")).click(); // 使用显示等待方式 ,确定页面已经加载完成,页面底部的关键字“搜索帮助已经显示在页面上” (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver d) { return d.findElement(By.id("s_footer")).getText().contains("搜索帮助"); } }); Assert.assertTrue(driver.getPageSource().contains(searchResult)); Log.endTestCase("TestSearch"); } @BeforeMethod public void beforeMethod() { OpenBrowserInfo.Log4jInitialize(); OpenBrowserInfo.SystemSetProperty(); driver = new FirefoxDriver(); } @AfterMethod public void afterMethod() { driver.quit(); } // 读取CSV文件的静态方法,使用CSV文件的绝对文件路径作为函数参数; public static Object[][] getTestData(String fileName) throws IOException { List<Object[]> records = new ArrayList<Object[]>(); String record; // 设定UTF-8字符编码集,使用带缓冲区的字符输入流BufferedReader 读取文件内容; BufferedReader file = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "UTF-8")); // 忽略读取CSV文件的标题行(第一行!); file.readLine(); /* * 遍历读取CSV文件中除第一行外其他所有内容,并存在在名为records的ArrayList中 * 每一个records中存储的对象为一个String数组; */ while ((record = file.readLine()) != null) { String fields[] = record.split(","); records.add(fields); } // 关闭文件对象; file.close(); // 第一函数返回值,即Object[][] // 将存储测试数据的list 转换为一个Objectde 的二维数组; Object[][] results = new Object[records.size()][]; for (int i = 0; i < records.size(); i++) { results[i] = records.get(i); } return results; } }