Writing automated tests with Spock — groovy — Part II
This is a continuation of part I, if you need any prior briefing to this, please see: part I
By the end of this tutorial, you will be able to.
- Set up your IDE ready to write spock groovy tests
- Ran the spock groovy test described below.
Pre-requisites
- Have intelliJ installed. If you do not have that installed — visit intellij and get a community edition.
- Have some basic knowledge of java/groovy — checkout groovy website for more info.
- Have some basic knowledge about gradle.
— Setting up our ide for our first test:
1. Open up your intellij and click file > new > Project > gradle(on the left pane) > groovy(on the right pane)
2. Click next — give your project a groupId and artifactId
3. Ensure gradle JVM is selected and is correct, click next
4. Click finish
5. Add spock framework and http builder dependency in your build.gradle file as shown below. (the version may defer) depending on when you are reading this.
Note: The httpBuilder dependency will provide us with a Client for making requests to the target APIs.
Writing the first test:
Create your first Spec under src > test > groovy package. I have named it ColorSpec. Feel free to name it as you like.
import com.google.gson.Gson
import groovy.json.JsonSlurper
import groovyx.net.http.HTTPBuilder
import spock.lang.Shared
import spock.lang.Specification
class ColorsSpec extends Specification {
@Shared private Gson gson = new Gson()
def "test that a hex color returned expected rgb, hsl values"()
{
when: '''the color-api GET endpoint is invoked
with a query of hex 00ffa6'''
def client = new
HTTPBuilder('http://www.thecolorapi.com/') def response = gson.toJson(client.get(
path : 'id', query: ['hex':'00ffa6']))
then: "rgb values should be 0, 255, 166"
//parse response to JSON
def jsonResponse = new JsonSlurper().parseText(response)
//assert hex value is similar to what we are testing
jsonResponse.hex.value == "#00FFA6"
//assert (r,g,b) values are as expected
jsonResponse.rgb.r == 0
jsonResponse.rgb.g == 255
jsonResponse.rgb.b == 166
//assert (h,s,l) values are as expected
jsonResponse.hsl.h == 159
jsonResponse.hsl.s == 100
jsonResponse.hsl.l == 50
}
}
Running a spock test:
It’s super easy to run a spock test! Right click on the green arrow on intelliJ and click run!
In the next steps, we will add spock reports and use different annotations to improve our test.
Thanks for reading!
Setting up our ide for our first test:
- Open up your intellij and click file > new > Project