Saturday, January 27, 2018

Integration Testing first RESTful web service with Kotlin and Spring Boot

We have been building a lot of infrastructure using Kotlin and Spring Boot -- And I am loving it! I have decided to start documenting parts of it for my own reference. I also hope my rant is useful to someone else, who's trying to solve similar problems :D

In this post we will be looking at building our very first RESTful web service using Kotlin and Spring Boot and writing an integration test for it. We will be using Gradle as our build tool.

Gradle File

First important component in the puzzle is the Gradle file. Following is the complete gradle file that we will be using for this post. Notice the use of all-open plugin. This is needed so that Spring can Autowire dependencies into our Kotlin classes.


Code

Lets create a very simple Book data class, it has got properties like title and author.


Adding a BookController, it has only one method which serves the requests from /books/search?title={title} path. This method will return the details of the books whose titles contain the searched term.

Note: The books collection is hardcoded for this example but nothing stops us from getting it from an external source, e.g. a database.


Next we need to add the application class which will expose the main method.


Test

The fun part about Spring Boot + Kotlin is the ease of testing this service. We will test this service out in two ways

  • Testing the API in browser
  • Writing a integration test 

Browser Test
  • Boot up the server using the following command
  • If everything goes great you should see a message informing that the server is up and running.
  • Open up the browser and open the http://localhost:8080/books/search?title=Steve
  • You should see the following response in the browser

Integration Test

Spring Boot provides a convenient class TestRestTemplate to test out the REST api's. Here is an example test for testing our API


As you run the test, notice that it boots up the server, invokes the api and fires the asserts on the responses!

Bonus

The toJson and fromJson methods are extension methods, they convert Objects into JSON representation and visa-a-versa. I use them all the time, they are pretty handy!

Project Structure

The best way to show this is via a screenshot.


Thats about it, we have a web service written in Kotlin using Spring Boot and we have successfully written a test for it as well!

PS: Here is the complete source code of the example used in this post


Have some Fun!