本节是关于前端应用的功能测试。Spock
没有提供原生浏览器支持,所以得借助Geb
来实现。
Geb浏览器自动化
Geb是对Selenium/WebDriver
自动化框架的封装,如果了解过Selenium
,那么Geb
理解就轻而易举。Geb
使用类jQuery
语言操作页面内容句号。如下代码为例:
$("h2").text()
👆获取h2标签的文本
👇点击按钮
$("#myButton").click()
例子
Spock和Geb:天作之合
以验证首页标题为例:
class HomePageSpec extends GebSpec {//继承GebSpec
def "Trivial Geb test for homepage"() {
when: "I go to homepage"
Browser.drive {
go "http://localhost:8080/web-ui-example/index.html"//加载url
}
then: "First page should load"
title == "Spock/Geb Web example"//判断title
}
}
👆最重要的是必须继承GebSpec
类而不是Spock
的Specification
。接下来验证页面h1
元素的内容:
def "Trivial Geb test for homepage -header check"() {
when: "I go to homepage"
Browser.drive {
go "http://localhost:8080/web-ui-example/index.html"
}
then: "First page should load"
title == "Spock/Geb Web example"
$("h1").text() == "Java Testing with Spock - Sample code"
$(".active").text() == "Welcome"
}
👆h1
元素的内容是"Java Testing with Spock - Sample code"
,当前标签是Welcome
。
页面元素交互
接下来模拟用户交互行为:填写产品名称和价格并新建产品:
@Stepwise
class AddProductGebSpec extends GebSpec {
def "Navigation to page"() {
when: "I go to the new product page"
Browser.drive {
go "http://localhost:8080/web-ui-example/add-product.html"//进入页面
}
then: "the form should load"
$(".col1").$("h2").text() == "New Product details"//确认进入页面
}
def "Creation of new product"() {
when: "I fill in product details"
$("input[name='productName']").value("Bravia TV")//输入产品名称
$("#createProductButton").click()//点击按钮
then: "I should see a success message"
$(".ok").text() == "You added new product named: Bravia TV."//验证创建成功消息
}
}
👆@Stepwise
注解限制测试按序执行,
$(".col1").$("h2").text() == "New Product details"
👆确认到达正确页面,
$("input[name='productName']").value("Bravia TV")
$("#createProductButton").click()
👆模拟用户输入产品名称并点击创建产品按钮。其它Geb
使用方式可参考官网(特别留意Page Objects
模式)。