REST Assured is an easy to use library for the JVM that allows you to test REST/HTTP based services. It has good support for Java, Groovy and Scala and in this blog post I want to share some small tips to make the Kotlin integration even smoother.
Kotlin is a pretty interesting language developed by JetBrains that will look familiar if you’re used Java, Groovy and Scala. Let’s pretend that we want to test the following resource written in Sinatra:
require 'json'
require 'sinatra'
get '/greeting' do
content_type :json
firstName = params['firstName']
lastName = params['lastName']
{ :greeting =>
{ :firstName => firstName,
:lastName => lastName }}.to_json
end
If we invoke this service with for example curl:
curl "http://localhost:8080?firstName=Johan&lastName=Haleby"
it’ll return the following JSON:
{
"greeting":{
"firstName":"Johan",
"lastName":"Haleby"
}
}
Writing a simple test case for this service in Kotlin is straight forward:
package se.haleby.kotlin
import com.jayway.restassured.RestAssured.given
import org.hamcrest.Matchers.equalTo
import org.junit.Test
class RestAssuredKotlingExampleTest {
Test fun kotlin_rest_assured_example() {
given().
param("firstName", "Johan").
param("lastName", "Haleby").
`when`().
get("/greeting").
then().
statusCode(200).
body("greeting.firstName", equalTo("Johan")).
body("greeting.lastName", equalTo("Haleby"))
}
}
However you may notice that we have to escape the when
function because when
is a reserved keyword in Kotlin. So what we’re going to do is to add an extension function called When
that we can use as an alias to avoid manual escaping. We can do this by for example defining a trait like this:
package se.haleby.kotlin
import com.jayway.restassured.specification.RequestSpecification
trait RestAssuredSupport {
fun RequestSpecification.When(): RequestSpecification {
return this.`when`()
}
}
Now that we’ve added the alias we import the trait and use it like this:
package se.haleby.kotlin
import com.jayway.restassured.RestAssured.given
import org.hamcrest.Matchers.equalTo
import se.haleby.kotlin.RestAssuredSupport
import org.junit.Test
class RestAssuredKotlingExampleTest : RestAssuredSupport {
Test fun kotlin_rest_assured_example() {
given().
param("firstName", "Johan").
param("lastName", "Haleby").
When().
get("/greeting").
then().
statusCode(200).
body("greeting.firstName", equalTo("Johan")).
body("greeting.lastName", equalTo("Haleby"))
}
}
Voila! Now we don’t need to escape when
anymore and the code looks nicer. Thanks to Jasper Blues for bringing this to attention.
One thought on “REST Assured with Kotlin”
Hey,
Just to let you know traits keyword is redundant in this example. It is now interface