UI自动化实战
上节笔记中记录了如何添加dependencies,这一笔记中,介绍的是如何使用webdriver做自动化UI测试(用webdriver manager自动管理驱动)
当pom.xml文件里添加好了对应的dependencies,就可以使用maven命令来安装,mvn install 就可以装pom文件里的所有依赖了。安装完后,建一个测试用例 (以CRM zoho为例子):
package testcase;
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import io.github.bonigarcia.wdm.WebDriverManager;
public class TestZohoLogin {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
WebDriverManager.firefoxdriver().setup();
// 初始化 FirefoxDriver
WebDriver ffdriver = new FirefoxDriver();
ffdriver.get("https://accounts.zoho.com/signin");
ffdriver.findElement(By.xpath("//input[@id='login_id']")).sendKeys("username");
WebElement nextEl = ffdriver.findElement(By.xpath("//span[contains(text(),'下一步')]"));
// 创建一个 Duration 对象,表示等待的持续时间
Duration timeout = Duration.ofSeconds(10);
// 使用 Duration 对象创建 WebDriverWait 对象
WebDriverWait wait = new WebDriverWait(ffdriver, timeout);
wait.until(ExpectedConditions.elementToBeClickable(nextEl)).click();
ffdriver.findElement(By.xpath("//input[@id='password']")).sendKeys("password");
WebElement loginEl = ffdriver.findElement(By.xpath("//button[@id='nextbtn']"));
wait.until(ExpectedConditions.elementToBeClickable(loginEl)).click();
Thread.sleep(3000);
}
}
note: 页面元素的xpath查找,可以建议使用firefox里的插件 SelectorsHub。 非常好用,具体使用可以参考____SelectorsHub简介_____