首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spock中的数据驱动测试

Spock中的数据驱动测试
EN

Stack Overflow用户
提问于 2016-06-08 20:07:37
回答 3查看 823关注 0票数 0

我正在将一些JUnit测试重写到Spock中,以利用数据驱动的测试风格。

我有点纠结于如何为验证提供一些动态的东西。

到目前为止,我的情况如下:

代码语言:javascript
复制
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。

我想那是因为关闭是在那个时候进行的,而不是刚刚宣布的。

有办法做得更好吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-06-08 20:21:36

代码语言:javascript
复制
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'
}

以上这些应该能帮助你走上正确的轨道。注意,您应该只在示例中有一些值。如果在断言中需要一些逻辑,请使用一个值,该值指示需要进行何种断言.但用闭包作为例子是个坏主意。

票数 1
EN

Stack Overflow用户

发布于 2016-06-08 20:34:28

变化

代码语言:javascript
复制
def "domestic rules"(from, to, oneWay, check) {

代码语言:javascript
复制
@Unroll
def "domestic rules from #from to #to one way #oneWay"() {
票数 2
EN

Stack Overflow用户

发布于 2016-06-08 21:34:38

如果您真的想让您的测试很难维护和继续,并在示例中使用闭包作为“值”,那么可以这样做:

代码语言:javascript
复制
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。这并不难,但至少要花几个小时!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37711960

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档