Spock - Introduction

Spock 

Introduction

Spock is a comprehensive and specification based testing framework for JAVA & Groovy. It helps to automate many boring repetitive tasks and manual task during application testing.

  • Super set of JUnit because Spock = JUnit + JBehave + JMock
  • Known as Enterprise testing application framework

Why Spock?

  1. Easy to learn (if you know JAVA / Groovy)
  2. Readability
  3. Provide detailed information about Exception
  4. Integration with Maven & Gradle

Required Jar:

Dependencies:

Simple Test Case in Spock:

def "should return 2 from first element of list"() {
    given:
        List<Integer> list = new ArrayList<>()
    when:
        list.add(1)
    then:
        2 == list.get(0)
}

Of course as the above test is broken (we are putting 1 into list and then expect 2 to be retrieved) test will fail. Spock will display a clear and easy to understand error message, explaining precisely what went wrong.
Error Message:

Condition not satisfied:
2 == list.get(0)
  |  |    |
  |  [1]  1
  false

Please take notice how clear a declaration of a test in Spock is. Developers do not have to follow the standard naming convention for methods and instead can declare the name of a test between two apostrophes. Thanks to that creating long but descriptive names for tests seems more natural and as well allows others to better understand what the purpose of a test it.

Given section

First of all we want to specify the context within which we would like to test a functionality. This is where you want to specify the parameters of your system/component that affect a functionality that is under the test. This section tends to get really big for all Spock rookies, but ultimately you will learn how to make it more concise and descriptive.

When section

This is where we can specify what we want to test. In other words what interaction with tested object/component we would like to study.

Then section

Now, here we verify what the result of the action performed in when section was. I.e. what was returned by the method (black box test) or what interactions have taken place in mocks and spies used inside tested function (white box test).

Alternative sections

In Spock documentation you will be able to find some alternatives for the above sections, e.g. setup, expect. The latter one is particularly interesting as it allows to create an extremely tiny tests.

def "should calculate power of number 2"() {
   expect:
      Math.pow(2) == 4
}



Comments