如何使用 Selenium 進行 UI 測試?
我們可以使用 Selenium webdriver 進行 UI 測試。為了實現這一點,我們必須遵循下面列出的步驟,這些步驟可以應用於開發的任何用於測試應用程式 UI 的指令碼 -
步驟 1 - 應建立 Webdriver 的物件。例如,
WebDriver driver = new ChromeDriver();
以上程式碼用於建立 webdriver 例項並在 Chrome 瀏覽器中啟動指令碼執行。
步驟 2 - 啟動我們要在其上執行 UI 測試的 URL。例如,
driver.get("https://tutorialspoint.tw/about/about_careers.htm");以上程式碼將啟動作為引數傳遞給 get 方法的 URL。
步驟 3 - 使用任何定位器(如 id、class、name、tagname、link text、partial link text、css 或 xpath)識別 webelement。方法 - findElement 用於使用這些定位器識別元素。例如,
WebElement elm = driver.findElement(By.tagName("h4"));以上程式碼用於使用定位器 tagname 識別元素。
步驟 4 - 定位元素後,對其執行操作,如輸入文字、點選等。例如,
elm.sendKeys("Selenium");以上程式碼用於在步驟 3 中識別的元素上輸入文字。
步驟 5 - 驗證在步驟 4 中執行操作對網頁的影響。例如,
Assert.assertEquals(s, "Selenium");
以上程式碼用於比較和驗證實際值是否等於預期值 - Selenium。
步驟 6 - 執行測試並記錄使用測試框架建立的結果。
步驟 7 - 透過退出 webdriver 會話完成測試。例如,
driver.quit();
示例
程式碼實現
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
public class NewTest {
@Test
public void f() {
System.setProperty("webdriver.chrome.driver", "chromedriver");
//webdriver instance
WebDriver driver = new ChromeDriver();
// implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//url launch
driver.get("https://tutorialspoint.tw/index.htm");
//element identify
WebElement elm = driver.findElement(By.tagName("input"));
//perform action - input text
elm.sendKeys("Selenium");
String s = elm.getAttribute("value");
//validate result with Assertion
Assert.assertEquals(s, "Selenium");
//quit browser
driver.quit();
}
}輸出

廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP