spock unit test loops in then clause
Asked Answered
R

1

21

I have a test with loops in the then clause:

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

for (String obj : result2) {
  obj.name.contains("foo")
  obj.entity.subEntity == "bar"
}

Newly I recognized that the loops are not really tested. No matter whether I have foo or bar or anything else, the test is always green :) I found out, that loops have to be tested differently, e.g. with 'every'? But just changing the 'each' to 'every' throws exception:

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" }

How should I correctly use loops in my test? I am using spock 0.7-groovy-2.0

Ramonramona answered 5/3, 2013 at 13:11 Comment(0)
E
44

Either use explicit assert statements:

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

Or a single boolean expression within every:

result.every {
    it.name.contains("foo") && it.entity.subEntity == "bar"
}
Euphuism answered 5/3, 2013 at 16:22 Comment(2)
Warning! First approach will generate more readable failure messages but will be evaluated to false (and operation fail) in case of result is empty collection!Potbelly
Additional warning: second method may run into presently unresolved bug if the closure you pass to every is multiple lines.Sunburst

© 2022 - 2024 — McMap. All rights reserved.