我正在将一些JUnit测试重写到Spock中,以利用数据驱动的测试风格。
我有点纠结于如何为验证提供一些动态的东西。
到目前为止,我的情况如下:
def "domestic rules"(from, to, oneWay, check) {
expect:
String mealResponse = getMealResponse(new BookingOptions.BookingOptionsBuilder().setFrom(from).setTo(to).setOneWay(oneWay).build());
check(mealResponse)
where:
from | to | oneWay || check
'MNL' | 'PEK' | true || assertNoMeals()
}
def assertNoMeals = {
assert JsonAssert.with(it)
.assertThat('$.links', hasSize(1))
.assertThat('$.links[0].rel', is("http://localhost:9001/api/docs/rels/ink/meal-allocations"))
.assertThat('$.links[0].uri', startsWith("http://localhost:9001/api/tenants/acme/meals/allocations/"));
}不幸的是,我在第一行数据中得到了一个NullPointerException。
我想那是因为关闭是在那个时候进行的,而不是刚刚宣布的。
有办法做得更好吗?
发布于 2016-06-08 20:21:36
def "domestic rules"() {
when: 'get meals using certain parameters'
String mealResponse = getMealResponse(new BookingOptions.BookingOptionsBuilder().setFrom(from).setTo(to).setOneWay(oneWay).build())
then: 'the json response should contain some contents (improve the message here!)'
JsonAssert.with(mealResponse)
.assertThat('$.links', hasSize(1))
.assertThat('$.links[0].rel', is(somethingToUseInAssertions))
where:
from | to | oneWay || somethingToUseInAssertions
'MNL' | 'PEK' | true || 'just some example'
}以上这些应该能帮助你走上正确的轨道。注意,您应该只在示例中有一些值。如果在断言中需要一些逻辑,请使用一个值,该值指示需要进行何种断言.但用闭包作为例子是个坏主意。
发布于 2016-06-08 20:34:28
变化
def "domestic rules"(from, to, oneWay, check) {至
@Unroll
def "domestic rules from #from to #to one way #oneWay"() {发布于 2016-06-08 21:34:38
如果您真的想让您的测试很难维护和继续,并在示例中使用闭包作为“值”,那么可以这样做:
def "domestic rules"() {
when:
String mealResponse = getMealResponse(new BookingOptions.BookingOptionsBuilder().setFrom(from).setTo(to).setOneWay(oneWay).build())
then:
check(mealResponse)
where:
from | to | oneWay || check
'MNL' | 'PEK' | true || this.&assertNoMeals
}
boolean assertNoMeals(mealResponse) {
assert JsonAssert.with(mealResponse)
.assertThat('$.links', hasSize(1))
.assertThat('$.links[0].rel', is("http://localhost:9001/api/docs/rels/ink/meal-allocations"))
.assertThat('$.links[0].uri', startsWith("http://localhost:9001/api/tenants/acme/meals/allocations/"))
return true // pass!
}在编写更合理的东西之前,我建议您同时学习Groovy和Spock。这并不难,但至少要花几个小时!
https://stackoverflow.com/questions/37711960
复制相似问题