使用到相關技術:selenium+testng+log4j+maven
selenium主要產生driver、擷取頁面元素等。
testng主要Run程式,產生測試報告、管理用例執行順序、斷言等。
log4j主要用來列印log日誌。
maven主要統一管理外部引入的jar包,其中就包括selenium+testng+log4j jar包的管理。maven能自動處理jar包的依賴關係。
開始動手
1、eclipse中建立maven項目(就不具體講解了,網上很多教程)
2、maven項目建立成功後,修改pom.xml檔案,直接上代碼如下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>atf</groupId><artifactId>autoTest</artifactId><version>0.0.1-SNAPSHOT</version><name>autoTest</name><url>http://maven.apache.org</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.14</version></dependency><dependency><groupId>org.seleniumhq.selenium</groupId><artifactId>selenium-java</artifactId><version>2.45.0</version></dependency><dependency><groupId>org.testng</groupId><artifactId>testng</artifactId><version>6.9.9</version></dependency></dependencies></project>
3、項目結構如下:
解讀:
src/main/java目錄下原始碼,本例子中有三個類,分別是LoginPage.java LoginCace.java ProFileUtil.java
src/main/resources目錄下放設定檔LoginPage.properties
src/test/resources目錄下放chromedriver.exe(網上下載即可)
4、直接上代碼
LoginPage.properties
loginPage.userName=class,usernameloginPage.userPassword=name,passwordloginPage.submit=xpath,//button[@type='submit' and @class='btn btn-primary']
ProFileUtil.java
package com.atf.utils;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.util.Properties;import org.openqa.selenium.By;/** * 加載和解析設定檔 * * @author alzhang */public class ProFileUtil {Properties proerties;public ProFileUtil(){}// 加載設定檔方法public ProFileUtil(String propFile) {proerties = new Properties();FileInputStream in = null;try {in = new FileInputStream(propFile);proerties.load(in);} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {if (in != null) {try {in.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}// 解析設定檔public By parseProFile(String elementName) {// 根據變數elementName,從設定檔中讀取對應的設定物件。String by = proerties.getProperty(elementName);// 將設定檔中的定位類型存到byType變數中。將定位運算式的值存到byValue變數中。String byType = by.split(",")[0];String byValue = by.split(",")[1];switch (byType) {case "id":return By.id(byValue);case "name":return By.name(byValue);case "class":return By.className(byValue);case "tag":return By.className(byValue);case "link":return By.linkText(byValue);case "partiallinktext":return By.partialLinkText(byValue);case "css":return By.cssSelector(byValue);case "xpath":return By.xpath(byValue);default:throw new RuntimeException("輸入的定位類型未在程式中定義,類型為:" + byValue);}}}
LoginPage.java
package com.atf.pageElement;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import com.atf.utils.ProFileUtil;/** * 登陸頁類。返回登陸頁面元素對象 * * @author alzhang * */public class LoginPage {private WebElement element = null;// 指定頁面元素定位運算式設定檔的絕對檔案路徑private ProFileUtil pfu = new ProFileUtil("src/main/resources/LoginPage.properties");private WebDriver driver;public LoginPage() {}public LoginPage(WebDriver driver) {this.driver = driver;}// 擷取頁面原始碼的封裝方法public String getPageSource() {return driver.getPageSource();}// 返回登陸頁面的使用者名稱輸入框元素對象public WebElement userName() throws Exception {element = driver.findElement(pfu.parseProFile("loginPage.userName"));return element;}// 返回登陸頁面的使用者密碼輸入框元素對象public WebElement userPassword() throws Exception {element = driver.findElement(pfu.parseProFile("loginPage.userPassword"));return element;}// 返回登陸頁面的登陸按鈕元素對象public WebElement submit() throws Exception {element = driver.findElement(pfu.parseProFile("loginPage.submit"));return element;}}
LoginCace.java
package com.atf.testCase;import java.util.Arrays;import java.util.concurrent.TimeUnit;import org.apache.log4j.Logger;import org.openqa.selenium.WebDriver;import org.openqa.selenium.chrome.ChromeDriver;import org.openqa.selenium.chrome.ChromeOptions;import org.openqa.selenium.remote.DesiredCapabilities;import org.testng.Assert;import org.testng.annotations.AfterTest;import org.testng.annotations.BeforeTest;import org.testng.annotations.Test;import com.atf.pageElement.LoginPage;public class LoginCase {public WebDriver driver;private static Logger logger = Logger.getLogger(LoginCase.class);@Testpublic void testLogin() throws Exception {driver.get("此處填寫登陸頁面的URL:http://XXXXXX");LoginPage loginPage = new LoginPage(driver);logger.info("登陸用例開始");logger.info("不輸入使用者名稱和密碼,點擊登陸");loginPage.submit().click();Thread.sleep(1000);Assert.assertTrue(driver.getPageSource().contains("請輸入賬戶名"));logger.info("輸入使用者名稱,不輸入密碼,點擊登陸");loginPage.userName().sendKeys("18678945247");loginPage.submit().click();Thread.sleep(1000);Assert.assertTrue(driver.getPageSource().contains("請輸入密碼"));logger.info("輸入錯誤的密碼,點擊登陸");loginPage.userPassword().sendKeys("1234567");loginPage.submit().click();Thread.sleep(1000);Assert.assertTrue(driver.getPageSource().contains("使用者名稱或密碼錯誤"));logger.info("輸入正確的密碼,點擊登陸");loginPage.userPassword().clear();loginPage.userPassword().sendKeys("12345678");loginPage.submit().click();Thread.sleep(1000);Assert.assertTrue(driver.getPageSource().contains("查看所有創業公司"));logger.info("登陸用例結束");}@BeforeTestpublic void beforeMethod() {System.setProperty("webdriver.chrome.driver", "src/test/resources/chromedriver.exe");// 去掉瀏覽器中的“--ignore-certificate-errors”DesiredCapabilities capabilities = DesiredCapabilities.chrome();capabilities.setCapability("chrome.switches",Arrays.asList("--incognito"));ChromeOptions options = new ChromeOptions();options.addArguments("--test-type");capabilities.setCapability("chrom.binary","src/ucBrowserDrivers/chromedriver.exe");capabilities.setCapability(ChromeOptions.CAPABILITY, options);driver = new ChromeDriver(capabilities);driver.manage().window().maximize();driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);}@AfterTestpublic void afterMethod() {driver.quit();}}
今天就到此結束了,這是最最基本的selenium web自動化測試的架構封裝。此架構可以看出,如果登陸頁面的元素改變,我們只需維護LoginPage.properties這個設定檔即可。大大降低維護成本。
此架構還不完善,後續還會繼續封裝,添加driver工廠類,增加用例容錯性,使用testng.xml組織用例,資料驅動,用例結束後的測試資料處理等等。也是在一步一步摸索中。很多想法尚不成熟,如果架構中有任何不足或是有更好的方法或意見歡迎留言分享。謝謝大家。