webUI自動化測試框架(一):簡介和Demo入門

前言:selenium和webdriver是目前主流的ui自動化測試框架之一,selenium又稱爲selenium RC,基本原理爲js注入,而webdriver是直接利用了瀏覽器的native support(廠商支持)來操作瀏覽器,所以,對於不同瀏覽器,必須依賴一個特定的瀏覽器native component來實現把webdriver API轉化爲瀏覽器的native invoke。在我們new出一個webdriver時,selenium首先會確認瀏覽器的native component是否存在且版本匹配(所以在使用瀏覽器驅動時,需要檢查該驅動版本與selenium的版本是否匹配,不匹配則不可用),接着在目標瀏覽器中啓動一整套的Web service,這套web service使用了selenium自己設計定義的協議,可以模擬用戶操作瀏覽器做出一系列動作。更多信息可訪問官方的用戶手冊:http://www.seleniumhq.org/docs/


先列舉下關於【 webUI自動化測試框架】 本人打算編寫的博客,有興趣的童鞋歡迎持續關注,這也算是我在實際工作中的一些學習和實踐記錄,可能有些不對或者不完善的地方,歡迎各位童鞋指正:

webUI自動化測試框架(一):webdriver簡介和Demo入門

webUI自動化測試框架(二):代碼分層-基礎層

webUI自動化測試框架(三):代碼分層-對象庫層

webUI自動化測試框架(四):代碼分層-操作層及用例層

webUI自動化測試框架(五):持續集成及測試報告輸出


進入正題:

一、環境搭建

webUI自動化的環境搭建相比於app簡單的多,有jdk,有selenium jar包,有瀏覽器驅動就夠了。

1.前往官網下載selenium相關jar包:http://www.seleniumhq.org/download/,由於Google被牆,可到我的網盤下載,版本爲selenium-java-3.4.0:http://pan.baidu.com/s/1dENrX89

2.新建java project,將selenium jar包及lib目錄下的jar包add to build path即可。

3.webdriver常用的方法:

元素定位方法:By.id(id)、By.xpath(xpath)、By.linkText(linkText)、By.className(className)、By.cssSelector(selector);

點擊操作:driver.findElement(By.id(id)).click();

輸入:driver.findElement(By.id(id)).sendKeys("selenium");

獲取文本:driver.findElement(By.id(id)).getText();

獲取對象屬性值:driver.findElement(By.id(id)).getAttribute("屬性");

更多方法可查閱官網文檔。

4.接下來我們寫個demo。

package com.etyero.testcase;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class WebDriverDemo {
	private WebDriver driver;
	private String baseUrl = "http://www.baidu.com";
	private StringBuffer verificationErrors = new StringBuffer();

	@BeforeMethod
	public void setUp() throws Exception {
		String browserDriverUrl = "D:/work/workplace/webUITest/browserDriver/chromedriver.exe";// 瀏覽器驅動路徑
		//啓動chrome瀏覽器
		System.setProperty("webdriver.chrome.driver", browserDriverUrl);
		driver = new ChromeDriver();
		driver.manage().window().maximize();// 最大化瀏覽器
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);//設置操作超時時長,該設置是全局性的,即所有操作都最長等待30s

	}

	@Test
	/**
	 * 搜索selenium
	 * 
	 * */
	public void testLogin() throws Exception {
		driver.get(baseUrl);
		driver.findElement(By.id("kw")).clear();// 按id找到元素後,清空該元素
		driver.findElement(By.id("kw")).sendKeys("selenium");// 輸入selenium
		driver.findElement(By.id("su")).click(); //點擊搜索按鈕
	}

	@AfterMethod
	public void tearDown() throws Exception {
		driver.quit();
		String verificationErrorString = verificationErrors.toString();
		if (!"".equals(verificationErrorString)) {
			Assert.fail(verificationErrorString);
		}
	}
}


至此,你已經進了webdriver的大門了,歡迎加入~~




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章