Skip to content

Instantly share code, notes, and snippets.

@outofcoffee
Created July 25, 2017 20:07
Show Gist options
  • Save outofcoffee/6afd3e211b6ca09bb8e423fa1bc31f2a to your computer and use it in GitHub Desktop.
Save outofcoffee/6afd3e211b6ca09bb8e423fa1bc31f2a to your computer and use it in GitHub Desktop.
DSL for using RestAssured with Kotlin

DSL for using RestAssured with Kotlin

Example

        given {
            on {
                get("/orders/123") itHas {
                    statusCode(404)
                }
            }
        }

        given {
            jsonBody(mapOf(
                    "orderId" to "123",
                    "status" to "new"
            ))

            on {
                post("/orders") itHas {
                    statusCode(201)
                    header("Location", endsWith("/orders/123"))
                }
            }
        }

        given {
            on {
                get("/orders/123") itHas {
                    statusCode(200)
                }
            }
        }

Comparison with old RestAssured style

        given()
                .`when`()
                .get("/orders/123")
                .then()
                .statusCode(404)

        given()
                .body(mapOf(
                        "orderId" to "123",
                        "status" to "new"
                ))
                .contentType(ContentType.JSON)
                .`when`()
                .post("/orders")
                .then()
                .statusCode(201)
                .header("Location", endsWith("/orders/123"))

        given()
                .`when`()
                .get("/orders/123")
                .then()
                .statusCode(200)

    }
}

DSL methods

private fun given(block: RequestSpecification.() -> Unit): RequestSpecification = RestAssured.given().apply(block)
private fun RequestSpecification.jsonBody(body: Any): RequestSender = this.contentType(io.restassured.http.ContentType.JSON).body(body)
private fun RequestSpecification.on(block: RequestSender.() -> Unit): RequestSender = this.`when`().apply(block)
private infix fun Validatable<*, *>.itHas(block: ValidatableResponseOptions<*, *>.() -> Unit): ValidatableResponseOptions<*, *> = this.then().apply(block)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment