2 期望 Spock 中的块?

2 expect blocks in Spock?

我有以下通过的 Spock 测试:

def "test"() {
  given:
    def name = "John"
  expect:
    name.length() == 4
  when:
    name = name.concat(name)
  then:
    name.length() == 8
}

但是当我修改最后一个 then 块并使其成为 expect 块时...

// previous part same
  expect:
    name.length() == 8

我得到:

Groovy-Eclipse: Groovy:'expect' is not allowed here; instead, use one of: [and, then]

是不是因为一次测试不允许多个expect块?如果是这样,这是否记录在任何地方?有一个类似的测试 here 是用 given - expect - when - then 编写的,但不清楚为什么没有使用第二个 expect,尽管所断言的是相同的,只是被翻转了。

when-expect 只是一个关于 Spock 规范 DSL 的语法错误。编译器消息已经告诉您如何解决您的问题。在 when 之后,您需要 then(或者如果您想将 when 块分成多个部分,则首先需要 and)。相比之下,expect 是一种将 when-then 收缩成一个块,因为刺激和验证反应在一个条件下一起出现。块标签及其使用方法已记录在案 here.

Specifications as Documentation, you learn more about why you might want to use and and block labels. Under Invocation Order 下,您将了解与 then-and 相比,使用多个 then 块可以实现什么。

您可以在一个功能中使用多个 expect 块,没问题。但是在使用另一个 expect.

之前,您确实需要确保您的 when-then(如果有)是完整的

例如,这是一个有效的特征:

  def "my feature"() {
    given: true
    and: true
    and: true

    expect: true

    when: true
    and: true

    then: true
    and: true

    then: true

    expect: true
    and: true

    cleanup: true
  }