Geb 自动化技能
有关 TestMu AI 云执行的详细信息,请参考 reference/cloud-integration.md 和 shared/testmu-cloud-reference.md。
核心模式
基本测试 (Spock)
import geb.spock.GebSpec
class LoginSpec extends GebSpec {
def "使用有效凭据登录"() {
when:
to LoginPage
emailInput.value("[email protected]")
passwordInput.value("password123")
loginButton.click()
then:
at DashboardPage
welcomeMessage.text().contains("欢迎")
}
def "使用无效凭据登录时显示错误"() {
when:
to LoginPage
emailInput.value("[email protected]")
passwordInput.value("wrong")
loginButton.click()
then:
at LoginPage
errorMessage.displayed
errorMessage.text().contains("无效")
}
}
页面对象
class LoginPage extends geb.Page {
static url = "/login"
static at = { title == "登录" }
static content = {
emailInput { $("#email") }
passwordInput { $("#password") }
loginButton { $("button[type='submit']") }
errorMessage(required: false) { $(".error") }
}
}
class DashboardPage extends geb.Page {
static url = "/dashboard"
static at = { $(".dashboard").displayed }
static content = {
welcomeMessage { $(".welcome") }
userName { $(".user-name") }
}
}
Navigator API
$("css-selector")
$("div", class: "active")
$("input", name: "email")
$("div.items li", 0) // 第一个匹配项
$("div.items li").size() // 计数
// 操作
element.click()
element.value("文本")
element << "文本" // 附加文本
element.text()
element.displayed
element.@href // 属性
云执行:driver = new RemoteWebDriver(new URL(gridUrl), caps)
设置:依赖 geb-spock 和 selenium-support 的 Gradle 项目
在 TestMu AI 上执行云测试
设置环境变量:LT_USERNAME、LT_ACCESS_KEY
// GebConfig.groovy
environments {
lambdatest {
driver = {
def ltOptions = [
user: System.getenv("LT_USERNAME"),
accessKey: System.getenv("LT_ACCESS_KEY"),
build: "Geb 构建",
name: "Geb 测试",
platformName: "Windows 11",
video: true,
console: true,
network: true,
]
def caps = new ChromeOptions()
caps.setCapability("LT:Options", ltOptions)
new RemoteWebDriver(
new URL("https://hub.lambdatest.com/wd/hub"), caps)
}
}
}
运行:./gradlew test -Dgeb.env=lambdatest
运行:./gradlew test
深入模式
有关生产级模式,请参阅 reference/playbook.md:
| 章节 | 内容 |
|---|---|
| §1 项目搭建 | build.gradle、GebConfig.groovy、环境配置、等待配置 |
| §2 页面对象 | Content DSL、at 检查、可复用组件的模块 |
| §3 规范测试 | Spock 集成、使用 @Unroll 的数据驱动测试、@Stepwise 流程 |
| §4 等待与异步 | 等待预设、JavaScript 交互、弹窗/确认框 |
| §5 高级模式 | 文件上传/下载、窗口、框架、自定义扩展 |
| §6 API 测试 | 使用 Groovy JsonSlurper 的 REST API 规范 |
| §7 CI/CD 集成 | 带无头 Chrome 的 GitHub Actions、Gradle 缓存 |
| §8 调试表 | 12 个常见问题及其原因和解决方案 |
| §9 最佳实践 | 14 项 Geb 测试清单 |