Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spock unit test loops in then clause

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

like image 594
radio Avatar asked Mar 05 '13 13:03

radio


People also ask

What does >> mean in Spock?

The right-shift ( >> ) operator defines the return value or behavior of a stubbed method.

Is Spock better than JUnit?

As we can see, Spock has more readability and a clearer documented code, it does not need 3rd parties, and it is more powerful than JUnit. In the end, using Spock or JUnit or TestNG or anything else is absolutely up to you. They each have their pros and cons for sure.

What is @unroll in Spock?

@Unroll is to have each data driven iterations reported independently, as indicated in Spock's website.


Video Answer


1 Answers

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"
}
like image 95
Peter Niederwieser Avatar answered Sep 20 '22 07:09

Peter Niederwieser