Spock is a testing and specification framework with beautiful and highly expressive specification language inspired from JUnit, jMock, RSpec, Groovy, Scala, Vulcans, and other fascinating life forms. In this article, we will show how to test APIs using the Spock framework written in Groovy.

Add dependencies to Gradle build script

We are using gradle to build our project. Gradle is fast, less verbose and overall a better developer experience.

dependencies {
    implementation("org.codehaus.groovy:groovy-all:3.0.9")

    testImplementation(platform("org.spockframework:spock-bom:2.0-groovy-3.0"))
    testImplementation("org.spockframework:spock-core:2.0-groovy-3.0")
    testImplementation("com.athaydes:spock-reports:2.1.1-groovy-3.0") {
        isTransitive = false // this avoids affecting the version of Groovy/Spock
    }

    testImplementation("io.rest-assured:rest-assured:4.4.0")

    testImplementation("org.slf4j:slf4j-api:1.7.32")
    testRuntimeOnly("org.slf4j:slf4j-simple:1.7.32")
}

Create a Groovy class and extends Specification

By extending the Specification class, methods written in this class will be automatically detected as test cases.

class RestAssuredSpec extends Specification {
    ...
}

Set up the request spec

We will use a free json api from JSONPlaceholder. We set up a shared resource here so that we can test multiple endpoints without creating duplicate instances.

class RestAssuredSpec extends Specification {
    @Shared
    def requestSpec =
            new RequestSpecBuilder()
                    .setBaseUri("https://jsonplaceholder.typicode.com")
                    .build()

    ...
}

Call request and validate json response

Lastly, we call the request and validate that the response is exactly what we expected.

class RestAssuredSpec extends Specification {
    @Shared
    def requestSpec =
            new RequestSpecBuilder()
                    .setBaseUri("https://jsonplaceholder.typicode.com")
                    .build()

    def "validate json response"() {
        given: "set up request"
        def request = given(requestSpec)

        when: "get todos"
        def response = request.get("/users/1")

        then: "should 200 okay, response matching expected"
        response.then()
                .statusCode(200)
                .body("id", is(1))
                .body("name", is("Leanne Graham"))
                .body("company.name", is("Romaguera-Crona"))
    }
}

You can find the complete working code here.