Writing automated tests with Spock — groovy — part I

Roselyne Makena
2 min readJun 12, 2019

--

What is groovy?
Groovy is a lightweight version of Java programming language that rans on the JVM. It employs feature of both a static and dynamic programming language. To get more information about groovy, visit the official site here.

Spock is a framework that was developed with a purpose of writing automated tests for systems.

General Spock framework:
Let’s quickly scheme through the basic composition of a spock test method. We are going to use a real free to use color API (an api that converts different colors to different color formats). To test the API, we hit the API endpoint with a defined request and get the response with returned data. After this, we will write assertions against the results, we will then check whether — our tests pass or fail. Before jumping straight to the code, let’s look at the test method below to understand what a spock method consists of.

In this example we use an hex-rgb color converter to confirm what we expect as a valid response. On a very basic level, I came up with the following test cases.
- Test that hex color #ffaabb returns RGB(255, 170, 187)

def “test that hex color #ffaabb returns RGB(255, 170, 187)”given: “”
when: “the get color endpoint is invoked”
then: “RGB colors should match (255, 170, 187)”
end
  1. def “test that fetching data is successful”
// this is the part where the test description is given.
def “test that a hex color returned expected rgb, hsl values

2. given: “”

given: “”
//this sets up preconditions for the test to be run.

3. when: “”

when: “”
//this is a section where we hit the actual endpoint of the system under test

4. then: “”

then: “”
//This is an assertion space. Here, we make assertions to ensure that the responses returned assert to the expected conditions.

5. where: “”

where: “”
//this is a block that allows for different data sets to be tested in the test block. This test in particular, would ran xtimes, each time running with a different value as specified.

Exploring spock annotations.

  • Spock has several annotations that are used to make it easy for a tester to accomplish a goal. I will quickly go through a few.
    - @Title — gives a natural-language name to a spec
    -@Narrative — natural-language descrition to a spec
    -@Unroll — enables iterations on a test method to be reported independently
    -@See — References to external information related to a specification or feature.
    -@Stepwise —Declares that the spec’s feature methods should be run sequentially in their declared order
  • For a detailed list of the available annotations see: here.

Thanks for reading!
Please check out part II — where we write and run the first test!

--

--

Roselyne Makena
Roselyne Makena

Written by Roselyne Makena

Design thinking analytic. Born creative with design edge. Software QA Engineer. I write articles at: senseitechtips.com

No responses yet