selenium 数据驱动 (基于TestNG CSV)

新建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));		  
		}
		@BeforeMethod
		public void BeforeMethod(){
			 driver =new FirefoxDriver();
		}
		@AfterMethod
		public void AfterMethod(){
			driver.quit();
		}
		public static Object[][] getTestData(String fileName) throws IOException{
			List  records = new ArrayList();
			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


(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如下图所示)

selenium 数据驱动 (基于TestNG CSV)_第1张图片


(TestNG Report如下图所示:)

selenium 数据驱动 (基于TestNG CSV)_第2张图片


TestNG reports:

selenium 数据驱动 (基于TestNG CSV)_第3张图片





你可能感兴趣的:(测试)