跟着Rahul學到Framework,於是開始基於公司的項目搭建自己的Framework。
Data Driven部分對@Data Provider已經可以熟練運用,今天自己試了一下excel,後面再抽時間去搞Mysql Database。
在網上搜了一些Excel Data Driven的demo,不是太簡單就是太難,Rahul的太簡單都沒有適合自己的,重新去看了下蟲師的 6.3.3 讀取csv 文件 這一章節, 很簡單清晰,然後搜了一下excel和csv的區別,其實也可以通用,上一家櫻桃兒公司我們做Integration用的還都是excel convert to csv呢。於是打算開始碼csv,至少以後問起來,這塊兒不是盲點。
目的:針對項目,新建factory配置,能夠通過頁面元素定位到box或者dropdown,然後從excel表裏獲取數據,新建成功,繼續新建factory。可自動化實現從excel中讀取factory配置所需要的參數,循環建立多個factory。
上代碼:
Base.java
package resources;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import com.csvreader.CsvReader;
public class Base{
public static WebDriver driver;
public static Properties prop;
public static Logger logger = LogManager.getLogger(Base.class.getName());
public static FileInputStream fis;
static {
prop = new Properties();
try {
fis = new FileInputStream("E:\\selenium\\mavenRepo\\MavenProject\\src\\main\\java\\resources\\data.properties");
prop.load(fis);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public WebDriver initDriverBase() throws IOException{
prop = new Properties();
FileInputStream fis = new FileInputStream("E:\\selenium\\mavenRepo\\MavenProject\\src\\main\\java\\resources\\data.properties");
prop.load(fis);
String browserName = prop.getProperty("browser");
System.out.println("browser name :" + browserName);
if(browserName.contains("chrome")){
System.setProperty("webdriver.chrome.driver", System.getProperties().getProperty("user.dir")+"\\chromedriver.exe");
driver = new ChromeDriver();
}
else if(browserName.contains("firefox")){
driver = new FirefoxDriver();
}
else{
driver = new InternetExplorerDriver();
}
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
return driver;
}
public void getScreenShotBase(String result) throws IOException{
File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File("E://selenium//mavenRepo//ScreenShot//" + result + "screenshot.png"));
}
public ArrayList<String[]> readCSVFile(String filePath) throws IOException{
// ArrayList 用來保存數據
ArrayList<String[]> csvList = new ArrayList<String[]>();
// 一般用這編碼讀就可以了
CsvReader reader = new CsvReader(filePath, ',', Charset.forName("SJIS"));
// 跳過表頭,如果需要表頭,不要寫這句
reader.readHeaders();
while(reader.readRecord()){ // 逐行讀入除表頭的數據
csvList.add(reader.getValues());
}
reader.close();
for(int row=0; row<csvList.size(); row++){
System.out.println(csvList.get(row)[0]);
System.out.println(csvList.get(row)[1]);
System.out.println(csvList.get(row)[2]);
System.out.println(csvList.get(row)[3]);
System.out.println(csvList.get(row)[4]);
System.out.println(csvList.get(row)[5]);
System.out.println(csvList.get(row)[6]);
System.out.println(csvList.get(row)[7]);
System.out.println(csvList.get(row)[8]);
System.out.println("---------------------------");
}
return csvList;
}
}
ElementGCPI.java
package pageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
public class ElementGCPI {
public static WebElement loginText(WebDriver driver){
return driver.findElement(By.xpath("//p[@class='container-section-p']"));
}
public static WebElement usernameBox(WebDriver driver){
////img[contains(@alt,'g1')]
return driver.findElement(By.xpath("//input[contains(@class,'container-section-inputOne container-section-input')]"));
}
public static WebElement passwordBox(WebDriver driver){
return driver.findElement(By.xpath("//input[contains(@class,'container-section-inputTwo container-section-input')]"));
}
public static WebElement loginButton(WebDriver driver){
return driver.findElement(By.xpath("//div[@ng-click='fn_login()']"));
}
public static WebElement alertText(WebDriver driver){
return driver.findElement(By.xpath("//li[@ng-bind='alertTxt']"));
}
public static WebElement logoutButton(WebDriver driver){
return driver.findElement(By.xpath("//span[@title='退出當前賬號']"));
}
public static WebElement basicConfigButton(WebDriver driver){
return driver.findElement(By.xpath("//div[@id='id_basicManager_div']"));
}
public static WebElement factoryConfigButton(WebDriver driver){
return driver.findElement(By.xpath("//li[@id='plantFactoryId']"));
}
public static WebElement factoryCreateButton(WebDriver driver){
return driver.findElement(By.xpath("//*[@id='id_addNew']"));
}
public static WebElement factoryCreateNameBox(WebDriver driver){
return driver.findElement(By.xpath("//*[@id='form-field-1']"));
}
public static void factoryTypeDropdown(WebDriver driver, int index){
Select s = new Select(driver.findElement(By.xpath("//div[@class='widget-main']/div[1]/div[2]/select")));
s.selectByIndex(index);
}
public static void factoryZoneDropdown(WebDriver driver, int index){
Select s = new Select(driver.findElement(By.xpath("//div[@class='widget-main']/div[2]/select")));
s.selectByIndex(index);
}
public static WebElement factoryLeftXBox(WebDriver driver){
return driver.findElement(By.xpath("//*[@id='form-field-171']"));
}
public static WebElement factoryLeftYBox(WebDriver driver){
return driver.findElement(By.xpath("//*[@id='form-field-11']"));
}
public static WebElement factoryWidthBox(WebDriver driver){
return driver.findElement(By.xpath("//*[@id='form-field-1171']"));
}
public static WebElement factoryHeightBox(WebDriver driver){
return driver.findElement(By.xpath("//*[@id='form-field-1111']"));
}
public static WebElement factorySampleTimeBox(WebDriver driver){
return driver.findElement(By.xpath("//div[@id='allow_drag_move_id_addFactory']/div/div[5]/div/input"));
}
public static void factoryUnitDropdown(WebDriver driver, int index){
Select s = new Select(driver.findElement(By.xpath("//div[@class='widget-main']/div[5]/div[2]/select")));
s.selectByIndex(index);
}
}
測試類:
FactoryConfigTest.javapackage gcpi;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import org.openqa.selenium.By;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import pageAction.PageAction;
import pageObjects.ElementGCPI;
import resources.Base;
public class FactoryConfigTest extends Base{
@BeforeClass
public void setUp() throws Exception{
// navigate to url
driver = initDriverBase();
driver.get(prop.getProperty("url"));
// login
PageAction.login(driver, prop.getProperty("username"), prop.getProperty("password"));
Thread.sleep(2000);
driver.manage().window().maximize();
ElementGCPI.basicConfigButton(driver).click();
Thread.sleep(2000);
ElementGCPI.factoryConfigButton(driver).click();
Thread.sleep(2000);
}
@Test
public void createFactoryConfigTest() throws IOException, InterruptedException{
ArrayList<String[]> csvList = readCSVFile(prop.getProperty("csvfilePath"));
for(int row=0; row<csvList.size(); row++){
ElementGCPI.factoryCreateButton(driver).click();
// Read CSV file
// Refer to 蟲師 “6.3.3 讀取csv 文件”
ElementGCPI.factoryCreateNameBox(driver).sendKeys(csvList.get(row)[0]);
// String -> int : int i = Integer.parseInt(str)
ElementGCPI.factoryTypeDropdown(driver, Integer.parseInt(csvList.get(row)[1]));
ElementGCPI.factoryZoneDropdown(driver, Integer.parseInt(csvList.get(row)[2]));
ElementGCPI.factoryLeftXBox(driver).sendKeys(csvList.get(row)[3]);
ElementGCPI.factoryLeftYBox(driver).sendKeys(csvList.get(row)[4]);
ElementGCPI.factoryWidthBox(driver).sendKeys(csvList.get(row)[5]);
ElementGCPI.factoryHeightBox(driver).sendKeys(csvList.get(row)[6]);
ElementGCPI.factorySampleTimeBox(driver).sendKeys(csvList.get(row)[7]);
ElementGCPI.factoryUnitDropdown(driver, Integer.parseInt(csvList.get(row)[8]));
ElementGCPI.factoryCreateConfirmButton(driver).click();
Thread.sleep(2000);
ElementGCPI.AlertButton(driver).click();
Thread.sleep(2000);
logger.info("------row:"+ row + "---------");
int count = driver.findElements(By.xpath("html/body/div[5]/div/div/div/div/div[2]/table/tbody/tr")).size();
String element = "";
for(int i=0; i<count-1; i++){
element = driver.findElements(By.xpath("html/body/div[5]/div/div/div/div/div[2]/table/tbody/tr/td[2]")).get(i).getText();
logger.info("-------element---" + element);
logger.info("-----csvList.get(row)[1]:" + csvList.get(row)[0]);
if(element.equals(csvList.get(row)[0])){
break;
}
}
String expectedText = csvList.get(row)[0];
Assert.assertEquals(element, expectedText);
}
}
@AfterClass
public void tearDown(){
driver.quit();
}
}