转载:https://blog.csdn.net/heart_1014/article/details/52013173
使用@DataProvider注解定义当前方法中的返回对象CSV文件(存放测试数据)作为测试脚本的测试数据集进行数据驱动。
用法参考代码:
代码在搜索完成后使用显式等待方式,确认页面已经加载完成,页面底部的关键字"搜索帮助"已经显示在页面上
-
-
-
import java.io.BufferedReader;
-
import java.io.FileInputStream;
-
import java.io.IOException;
-
import java.io.InputStreamReader;
-
import java.util.ArrayList;
-
-
import java.util.concurrent.TimeUnit;
-
-
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;
-
-
public class TestDataByCSVFile {
-
private static WebDriver driver;
-
@DataProvider(name="searchData")
-
public static Object[][] data() throws IOException
-
-
return getSearchData("E:\\AutoData\\testData.csv");
-
-
@Test(dataProvider="searchData")
-
public void testSearch(String searchdata1,String searchdata2,String searchResult) {
-
-
driver.get("http://www.sogou.com/");
-
-
-
driver.findElement(By.id("query")).sendKeys(searchdata1+" "+searchdata2);
-
-
driver.findElement(By.id("stb")).click();
-
-
-
(new WebDriverWait(driver,3)).until(new ExpectedCondition<Boolean>(){
-
-
-
public Boolean apply(WebDriver d) {
-
return d.findElement(By.id("sogou_webhelp")).getText().contains("搜索帮助");
-
-
-
-
Assert.assertTrue(driver.getPageSource().contains(searchResult));
-
-
-
public void beforeMethod() {
-
-
System.setProperty("webdriver.firefox.bin", "D:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
-
-
driver=new FirefoxDriver();
-
-
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
-
-
-
-
public void afterMethod() {
-
-
-
-
-
public static Object[][] getSearchData(String FileNameroot) throws IOException{
-
List<Object[]> records=new ArrayList<Object[]>();
-
-
-
BufferedReader file=new BufferedReader(new InputStreamReader(new FileInputStream(FileNameroot),"UTF-8"));
-
-
-
-
while((record=file.readLine())!=null){
-
String fields[]=record.split(",");
-
-
-
-
-
-
Object[][] results=new Object[records.size()][];
-
-
for(int i=0;i<records.size();i++){
-
results[i]=records.get(i);
-
-
-
-
运行结果:
-
PASSED: testSearch("老九门", "演员", "赵丽颖")
-
PASSED: testSearch("X站警天启", "导演", "布莱恩·辛格")
-
PASSED: testSearch("诛仙青云志", "编剧", "张戬")
-
-
===============================================
-
-
Tests run: 3, Failures: 0, Skips: 0
-
===============================================
测试数据的CSV文件内容:
搜索关键词1,搜索关键词2,搜索结果
老九门,演员,赵丽颖
X站警天启,导演,布莱恩·辛格
诛仙青云志,编剧,张戬
注意:使用写字板程序编辑CSV文件内容,在保存文件时要将文件存储为UTF-8编码格式。
数据驱动测试二:使用TestNG和CSV文件进行数据驱动
原文:https://www.cnblogs.com/ceshi2016/p/9523442.html