使用testNG/CSV文件编写数据驱动

废话不多说直接上代码,看不懂勿喷,自己的笔记

package china;

import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
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.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;

public class TestDataDriverByCSVFile {
    public WebDriver driver;
    String baseUrl="http://www.sogou.com";
  @DataProvider(name="testData")
    public  static Object[][] words()throws IOException{
      return getTestData("d:\testData.csv");
  }
  @Test(dataProvider="testData")
  public void testSearch(String searchWord1,String searchWord2,String searchResult) {
      driver.get(baseUrl);
      driver.findElement(By.id("query")).sendKeys(searchWord1+""+searchWord2);
      driver.findElement(By.id("stb")).click();
      //显示等待10秒,等待页面跳转完成,并判断新页面是否出现“搜索帮助”字样
      (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));
  }
  @BeforeMethod
  public void beforeMethod() {
      
      System.setProperty("webdriver.chrome.driver", "C:\chromedriver\chromedriver.exe");
      driver=new ChromeDriver();
      
  }

  @AfterMethod
  public void afterMethod() {
      driver.quit();
      
  }
  public static  Object[][] getTestData(String fileName) throws IOException{
      List<Object[]>records=new ArrayList<Object[]>();
      String record;
      //设置字符集为UTF-8
      BufferedReader file=new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "UTF-8"));
      file.readLine();//忽略CSV文件的标题行(第一行)
      //遍历读取文件中除第一行外的其它所有行内容,并存储在名为records的ArrayList中,每一个records中存储的对象为一个string数组;
      while((record=file.readLine())!=null){
          String fields[]=record.split(",");
          records.add(fields);
      }
      //关闭文件
      file.close();
      //定义函数返回值Object[][],将list转换为一个Object的二维数组;
      Object[][] results=new Object[records.size()][];
      //设置二维数组每行的值,每行是一个Object对象
      for(int i=0;i<records.size();i++){
          results[i]=records.get(i);
      }
      return results;
  }

}
原文地址:https://www.cnblogs.com/wangyinxu/p/6430140.html