自动化测试用例生成:AI 辅助的软件测试脚本编写
FreeGuideOnline
最新
2026-06-25
python import unittest from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC
class TestLogin(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() self.driver.get("https://example-login.com") self.wait = WebDriverWait(self.driver, 10)
def test_valid_login(self):
driver = self.driver
driver.find_element(By.ID, "email").send_keys("user@test.com")
driver.find_element(By.ID, "password").send_keys("Test1234")
driver.find_element(By.CSS_SELECTOR, "button[type='submit']").click()
# 等待跳转并验证
self.wait.until(EC.url_contains("/dashboard"))
welcome_text = driver.find_element(By.CSS_SELECTOR, ".welcome-message").text
self.assertIn("Welcome, User", welcome_text)
def test_invalid_login(self):
driver = self.driver
driver.find_element(By.ID, "email").send_keys("user@test.com")
driver.find_element(By.ID, "password").send_keys("wrongpass")
driver.find_element(By.CSS_SELECTOR, "button[type='submit']").click()
# 验证错误提示
error = self.wait.until(
EC.visibility_of_element_located((By.CLASS_NAME, "error-message"))
)
self.assertEqual(error.text, "Invalid credentials")
def tearDown(self):
self.driver.quit()
if name == "main": unittest.main()
### 提示词技巧总结
- **明确测试目标**: 给出 URL、元素定位参考(如 ID、class)
- **拆分场景**: 每个场景一个函数,方便断言与报告
- **指定期待行为**: 跳转 URL、文本内容、元素可见性
- **要求现代实践**: 显式等待、Page Object 模式(可在后续提示中要求重构)
通过多轮对话,你可以让 AI 进一步补充边界值测试、参数化、生成 Page Object 结构,甚至输出对应的 YAML/JSON 数据驱动文件。
---
## 如何将 AI 生成集成到 CI/CD 流程
AI 生成测试用例不是一次性的,应当融入持续的流水线中:
- 开发者提交代码 → 2. 需求文档自动更新 → 3. AI 解析新需求生成/更新测试脚本 → 4. 在测试环境中执行 → 5. 报告失败并自愈 → 6. 通过后部署