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() // 計數
// 動作
元素.click()
元素.value("text")
元素 << "text" // 附加文字
元素.text()
元素.displayed
元素.@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 測試檢查清單 |