spock单元测试循环在then子句中

rad*_*dio 16 testing loops clause spock

我在then子句中有一个带循环的测试:

result.each {
  it.name.contains("foo")
  it.entity.subEntity == "bar"
}

for (String obj : result2) {
  obj.name.contains("foo")
  obj.entity.subEntity == "bar"
}
Run Code Online (Sandbox Code Playgroud)

最近我意识到循环没有真正测试过.无论我是否有foo或bar或其他任何东西,测试总是绿色的:)我发现,循环必须以不同的方式进行测试,例如使用'every'?但只是将'each'更改为'every'抛出异常:

result.every {
  it.name.contains("foo")
  it.entity.subEntity == "bar"
}

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Spec expression: 1: expecting '}', found '==' @ line 1, column 61.
   s("foo") it.entity.rootEntity == "bar" }
Run Code Online (Sandbox Code Playgroud)

我应该如何在测试中正确使用循环?我正在使用spock 0.7-groovy-2.0

Pet*_*ser 28

使用显式断言语句:

result.each {
    assert it.name.contains("foo")
    assert it.entity.subEntity == "bar"
}
Run Code Online (Sandbox Code Playgroud)

或者在一个布尔表达式中every:

result.every {
    it.name.contains("foo") && it.entity.subEntity == "bar"
}
Run Code Online (Sandbox Code Playgroud)

  • 警告!第一种方法会生成更多可读的失败消息,但如果`result`为空集合,将被评估为`false`(并且操作失败)! (3认同)