1、使用 Java 和 Selenium WebDriver 创建一个自动化框架。前提条件是安装最新版本的 Java、你选择的集成开发环境(IntelliJ 是 Java 常用的 IDE)、Chrome 浏览器、Apache Maven 和 TestNG。请使用 Selenium WebDriver 编写测试代码,按照步骤设置项目、创建测试类,实现登录一个电子商务应用程序并验证主页标题的功能。
以下是使用 Java 和 Selenium WebDriver 创建自动化框架的详细步骤:
-
安装必备工具:
- 安装最新版本的 Java
- 选择的 IDE(如 IntelliJ)
- Chrome 浏览器
- Apache Maven
- TestNG -
配置 Maven:
- 下载 Maven 并按官网说明安装
- 在pom.xml文件中定义依赖库、插件及其版本,示例如下:xml <?xml version="1.0" encoding="UTF-8"?> <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"> ... </project> -
创建 Maven 项目:
- 打开 IntelliJ
- 选择“File” → “New” → “Project” → “Maven”
- 选择下载的 Java 版本
- 输入项目名称、位置、groupID 和 artifactID -
下载 ChromeDriver:
- 下载与本地 Chrome 浏览器版本兼容的 ChromeDriver 可执行文件
- 将其放在项目的src/main/resources文件夹下 -
添加项目依赖:
- 在pom.xml中添加 Selenium、Java 和 TestNG 库依赖
- 在 IntelliJ 的右侧 Maven 面板刷新并下载库 -
创建基础测试类:
- 在src/test/java下创建名为base的包
- 添加BaseTests.java类,代码如下:```java
package base;import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import java.time.Duration;public class BaseTests {
protected WebDriver driver;@BeforeMethod public void setUp(){ System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver"); driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10)); driver.get("http://eCommerce.com/sign_in"); } @AfterMethod public void teardown(){ driver.quit(); }}
``` -
创建页面类:
- 为应用的每个页面创建对应的页面类
- 页面类包含查找和交互元素的 Selenium WebDriver 方法
- 页面类可链式返回其他页面对象,例如:```java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;public class HomePage {
private WebDriver driver;
private By searchField = By.cssSelector(“input.searchBox”);public HomePage(WebDriver driver) { this.driver = driver; } public String getTitle(){ WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); wait.until(ExpectedConditions.presenceOfElementLocated(searchField)); return driver.getTitle(); }}
``` - <

最低0.47元/天 解锁文章
6685

被折叠的 条评论
为什么被折叠?



