Spock:可重复使用的数据表
问题描述:
我可以像这样进行测试并将where子句数据表提取到可重用块中吗?Spock:可重复使用的数据表
@Unroll
void "test that doSomething with #a and #b does not fail"(String a, String b) {
when:
doSomethingWithAandB(a, b)
then:
notThrown(Exception)
where:
a | b
"foo" | "bar"
"foo" | "baz"
"foo" | "foo"
}
是这样的(伪代码):
@Unroll
void "test that doSomethingElse with #a and #b does not fail"(String a, String b) {
when:
doSomethingElseWithAandB(a, b)
then:
notThrown(Exception)
where:
dataTable()
}
def dataTable(a, b) { // this is now reusable in multiple tests
a | b
"foo" | "bar"
"foo" | "baz"
"foo" | "foo"
}
答
是的,可以。
import spock.lang.Specification
import spock.lang.Unroll
class SampleTest extends Specification {
@Unroll
def "max of #a and #b gives #c"() {
expect:
Math.max(a, b) == c
where:
a << aProvider()
b << bProvider()
c << cProvider()
}
private List<Integer> aProvider() {
[1 ,2 ,4]
}
private List<Integer> bProvider() {
[0 ,2 ,5]
}
private List<Integer> cProvider() {
[1 ,2 ,5]
}
}
当然,aProvider/bProvider/cProvider可以重新写成“更巧妙的方式”和除其他事项外,可被外部的一些类,并在许多测试中重复使用。您不必指定表格,但可以提供'数据管道'。阅读Data Driven Testing章节。
答
谢谢,马克,为您的answer!根据我所了解的情况,我已经达到了一个相当简单的解决方案。在where
子句
import spock.lang.Specification
import spock.lang.Unroll
class SampleTest extends Specification {
@Unroll
def "max of #a and #b gives #c"() {
expect:
Math.max(a, b) == c
where:
params << dataTable()
a = params.a
b = params.b
c = params.c
}
// this is now reusable in multiple tests
def dataTable() {
return [
// case 1
[
a: 1,
b: 0,
c: 1
],
// case 2
[
a: 1,
b: 2,
c: 2
],
// case 3
[
a: 4,
b: 5,
c: 5
]
]
}
}
答
表格式的数据实际上被解析为一组的在编译时OR
表达式,收集到的列表的列表中,然后转置,所以这样的:
where:
a | b | c
1 | 0 | 1
2 | 2 | 2
4 | 5 | 5
将被改造成此:
where:
a << [1, 2, 4]
b << [0, 2, 5]
c << [1, 2, 5]
生成的测试方法之前(见org.spockframework.compiler.WhereBlockRewriter
细节)。这个var << list
结构在documentation中被称为“数据管道”。
升级现有答案位,作为斯波克1.1的,可以使用一种称为“多变量数据管道”构建体,其将转置表缩短了码的位:
class SampleTest extends Specification {
@Unroll
def "max of #a and #b gives #c"() {
expect:
Math.max(a, b) == c
where:
[a, b, c] << dataTable()
}
static def dataTable() {
[
[1, 0, 1],
[2, 2, 2],
[4, 5, 5]
]
}
}
有趣的事实:虽然docs on Syntactic Variations没有解释为什么,那是因为表行被解析为一组OR
表情,双杆也可以用 -
where:
a | b || c
1 | 0 || 1
2 | 2 || 2
4 | 5 || 5
看看这里:https://*.com/questions/26156544/using-spock-data-table-for-filling-objects – Opal