Using groovy closures in Spock where blocks

Groovy Spock vs Java jUnit

Because Spock is just jUnit under the hood we can do everything we can in jUnit and more because Spock uses groovy. One aspect of the jUnit test framework that most people don’t take advantage of is using parameterized classes – making the test class be test driven. The best part of this is you can run the same test with different variables, allowing all sorts of edge cases to be tested without having to rewrite the test class. Spock makes this visually very easy by using a where block. The first line of the where block is the variables that you want to use through out the test. The second line (and every line after that) is a new set of data that you want to test. Remember the test will run as many times as there are lines in the where block.

class testWithClosures extends Specification {

  def setupSpec() {
    //Runs before the class initialization 
  }

  def cleanupSpec() {
    //After the class tests run this will run
  }

  def "Some super awesome test with closures"() {
    when:
      Some conditional setup
    then:
      specialAssertion.call()

     where:
     specialAssertion | _
     { Whatever Code you want to special validate } | _ 
     { Another special case validation }
  }

}

The blessings of using Groovy with Spock

Using Groovy in Spock has one amazing perk. The example above lets you define a variable in the where block called specialAssertion. You can take advantage of closures in groovy by placing closures inside your where block and then calling them in your spec class. I occasionally use this if I want to do some special type of assertion with the data that I am passing to the spec. You don’t have to do assertions, but any type of code that needs to be called just for that line of data in the where block. This can be thought of as a similar polymorphic approach of abstract classes and methods.

Leave a Reply