Java 자동화 테스트 시리즈 [v 1.0.0] [데이터 구동 DPCsv]

14832 단어
package testNGWithDataDriven;
 
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.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;
 
public class TestNGCsvDriven {
    public WebDriver driver;
    String baseUrl = "http://www.sogou.com";
    //    DataProvider        “csvTestData”
    @DataProvider(name = "csvTestData")
    public static Object[][]words() throws IOException{
        //         getTestData,  CSV       
        return getTestData("F:\\TestNGWithDataDriven\\dataDriven\\src\\test\\java\\testData\\testData.csv");
    }
    @BeforeMethod
    public void beforeMethod(){
        driver = new ChromeDriver();
    }
    @Test(dataProvider = "csvTestData")
    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();
        Assert.assertTrue(driver.getPageSource().contains(searchResult));
    }
    @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   ,            BufferedRead      
        BufferedReader file = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "GBK"));
        //    CSV      
        file.readLine();
        /**                     
         *       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;
    }
}


좋은 웹페이지 즐겨찾기