Java Programming Tutorials

Java programming tutorials with many code examples!

Spock Framework basic test


Spock Framework is fantastic unit tests library that makes people love to test their code. Check out this post and learn how to start with Spock Framework!

Spock Framework properties:

  • concise and readable tests
  • ease of mocking and defining interactions
  • good integration with Maven and Gradle
  • using Groovy, which is more expressive language than Java

Spock‘s drawbacks:

  • need to learn a new language: Groovy
  • can’t mock statics, finals, etc. (only with Powermock)
  • very slow release cycles


Spock Framework test:

  • it’s a Groovy class and extends spock.lang.Specification,
  • has some: fields, setup, tests, helper methods,
  • instructs JUnit to execute test with Spock’s runner – Sputnik.

Example unit test:

import spock.lang.Specification

class BasicListTest extends Specification {
  def "should not be empty after adding element"() {
    // [] is Groovy literal for List and is infered
    def list = []


    // Asserts are implicit and not need to be stated.
    // Change "==" to "!=" and see what's happening!
    list.size() == 1
    list == [42]

given, when, then are Spock‘s labels which indicate test sections as in Behavior Driven Development. The test is very readable and easy to write.

Remember to install Spock Framework plugin if you are using Intellij IDEA!


Was it helpful? Share!