自动化测试核心知识梳理与 Java 代码详解
一、自动化测试概念
1. 什么是自动化测试?
- 定义:通过编写代码模拟用户操作,自动验证软件功能是否符合预期。
- 类比:就像用机器人代替人工点击按钮、输入数据,并自动检查结果是否正确。
2. 为什么需要自动化测试?
- 优势:
- 效率:重复执行速度快(如每日构建后的回归测试)。
- 准确性:避免人为疏忽。
- 覆盖率:覆盖复杂场景(如边界值、异常流程)。
- 适用场景:
- 核心功能频繁回归(如登录、支付)。
- 复杂计算逻辑验证(如金融利率计算)。
- 多环境兼容性测试(如不同浏览器、操作系统)。
3. 自动化测试类型
类型 | 工具/框架 | 适用场景 |
---|---|---|
单元测试 | JUnit, TestNG | 验证单个方法或类的逻辑正确性 |
接口测试 | RestAssured | 验证 API 接口功能和性能 |
UI测试 | Selenium | 验证用户界面交互流程 |
Selenium 是什么?
Selenium 是用于自动化浏览器操作的工具,能模拟人类在浏览器中的点击、输入、滚动等行为。
核心能力:
✅ 跨浏览器测试(Chrome/Firefox/Edge)
✅ 多语言支持(Java/Python/C#)
✅ 处理动态网页元素(如弹窗、下拉菜单)
二、环境搭建:5分钟快速配置
1. 添加 Maven 依赖
<!-- Selenium Java SDK -->
<dependency><groupId>org.seleniumhq.selenium</groupId><artifactId>selenium-java</artifactId><version>4.21.0</version>
</dependency><!-- Chrome 浏览器驱动 -->
<dependency><groupId>org.seleniumhq.selenium</groupId><artifactId>selenium-chrome-driver</artifactId><version>4.21.0</version>
</dependency>
2. 下载浏览器驱动
- ChromeDriver:访问 ChromeDriver官网
- 选择与本地 Chrome 版本匹配的驱动
- 解压后得到
chromedriver.exe
(Windows)或chromedriver
(Mac/Linux)
3. 配置驱动路径
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
WebDriver driver = new ChromeDriver(); // 启动浏览器
三、核心操作:从零编写第一个测试
1. 打开网页 & 关闭浏览器
public class BasicTest {WebDriver driver;@BeforeEachvoid setup() {System.setProperty("webdriver.chrome.driver", "chromedriver");driver = new ChromeDriver();}@Testvoid testOpenPage() {driver.get("https://www.baidu.com"); // 打开百度String title = driver.getTitle();assertEquals("百度一下,你就知道", title);}@AfterEachvoid teardown() {driver.quit(); // 关闭浏览器}
}
2. 元素定位八大方法
定位方式 | 代码示例 | 适用场景 |
---|---|---|
By.id | driver.findElement(By.id("kw")) | 元素有唯一ID |
By.name | driver.findElement(By.name("wd")) | 表单元素常用 |
By.className | driver.findElement(By.className("s_ipt")) | 通过CSS类名定位 |
By.tagName | driver.findElement(By.tagName("input")) | 按标签名定位(如 <input> ) |
By.linkText | driver.findElement(By.linkText("新闻")) | 精确匹配超链接文本 |
By.partialLinkText | driver.findElement(By.partialLinkText("新")) | 模糊匹配链接文本 |
By.xpath | driver.findElement(By.xpath("//input[@id='kw']")) | 复杂路径定位 |
By.cssSelector | driver.findElement(By.cssSelector("#kw")) | 类似jQuery选择器 |
3. 常用交互操作
// 输入文本
WebElement searchBox = driver.findElement(By.id("kw"));
searchBox.sendKeys("自动化测试"); // 输入关键词// 点击按钮
WebElement searchBtn = driver.findElement(By.id("su"));
searchBtn.click();// 获取元素文本
WebElement result = driver.findElement(By.className("c-title-text"));
String text = result.getText();
assertTrue(text.contains("测试"));// 清除输入框
searchBox.clear();
四、高级技巧:处理复杂场景
1. 等待机制(解决元素加载慢)
// 隐式等待(全局生效)
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));// 显式等待(针对特定元素)
WebElement element = new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfElementLocated(By.id("dynamicElement")));
2. 处理弹窗/Alert
// 获取弹窗并操作
Alert alert = driver.switchTo().alert();
alert.accept(); // 点击确认
// alert.dismiss(); // 点击取消
// String alertText = alert.getText(); // 获取弹窗文本
3. 下拉选择(Select 类)
WebElement dropdown = driver.findElement(By.id("city"));
Select select = new Select(dropdown);
select.selectByValue("shanghai"); // 按value选择
// select.selectByVisibleText("上海"); // 按显示文本
// select.selectByIndex(1); // 按索引
4. 文件上传
WebElement upload = driver.findElement(By.id("file-upload"));
upload.sendKeys("/path/to/file.txt"); // 直接发送文件路径
五、实战项目:电商网站测试
场景:用户登录 → 搜索商品 → 加入购物车
public class EcommerceTest {WebDriver driver;@BeforeEachvoid setup() {driver = new ChromeDriver();driver.manage().window().maximize(); // 最大化窗口}@Testvoid testShoppingFlow() {// 1. 登录driver.get("https://example.com/login");driver.findElement(By.id("username")).sendKeys("user123");driver.findElement(By.id("password")).sendKeys("pass123");driver.findElement(By.id("login-btn")).click();// 2. 搜索商品WebElement searchBox = driver.findElement(By.name("q"));searchBox.sendKeys("iPhone 15");searchBox.submit();// 3. 添加购物车WebElement product = new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[contains(text(),'iPhone 15')]")));product.click();driver.findElement(By.cssSelector(".add-to-cart")).click();// 验证购物车数量WebElement cartCount = driver.findElement(By.id("cart-count"));assertEquals("1", cartCount.getText());}@AfterEachvoid teardown() {driver.quit();}
}
六、最佳实践与调试技巧
-
元素定位失败怎么办?
- 使用浏览器开发者工具(F12)检查元素属性
- 尝试更换定位方式(优先用
id
>cssSelector
>xpath
) - 添加显式等待解决加载延迟问题
-
提高脚本稳定性
- 使用
Page Object 模式
分离页面元素和测试逻辑 - 避免使用绝对 XPath(如
//div/div[2]/span
) - 定期清理浏览器缓存(防止旧数据干扰)通过以上内容,您已掌握 Selenium 的核心操作和实战技巧!建议从简单场景入手,逐步挑战复杂业务流程测试。
- 使用