是否可以像这样在 where 块中传递一个值。
我试过这个。但它失败并给出 MissingPropertyException。
我希望 name1 和 name2 位于方法内部。
def "length of names #name"() {
def name1 = "Spock"
def name2 = "Java"
expect:
name.size() == length
where:
name || length
name1 || 5
name2 || 2
}
最佳答案
测试数据属于 where 块,在测试(特征)方法中没有硬编码。
看到这一点的一种粗略方法是将测试主体(不包括 where 块)视为具有一定数量参数的方法 - 在您的情况下为 2,名称和长度。然后意识到 where 子句只是向测试运行程序提供数据值,以便在调用您的测试方法时使用。
Spock 使用 Groovy 魔法进行转换
def "test length of names"() {
expect:
name.size() == length
where:
name | length
"Spock" | 5
"Java" | 4
}
大致像def test_length_of_names(name, length) { // note the arguments
assert name.size() == length
}
然后告诉测试运行程序为 where 子句中的每一行调用一次测试test_length_of_names("Spock", 5)
test_length_of_names("Java", 4)
这种方法此解释遗漏了一些细节,例如为每个测试创建规范的实例、更新每个测试调用的名称以及调用各种设置和清理方法。
见 the Spock documentation更多细节。
关于unit-testing - 在 : block in Spock test 中传递一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19015236/