Ktor REST Apis — Part 3 (Testing Routes)

Saurabh Pant
ProAndroidDev
Published in
2 min readOct 31, 2021

--

Image by depositphotos.com

In case, to set up the Ktor project, checkout

In case, to build the APIs using Ktor, checkout

This is the last part of the series in which we’ll test our apis created in previous part II. To recall, we’ve created the following APIs

POST : Add a dog : http://127.0.0.1:8080/dogs

GET : Get all dogs : http://127.0.0.1:8080/dogs

GET : Get dog by id: http://127.0.0.1:8080/dogs/{id}

DELETE : Delete dog by id: http://127.0.0.1:8080/dogs/{id}

We’ll test the APIs firstly by writing test cases and will see if they are working fine. For the same, Ktor provides a module function which let us test the apis without starting the actual server but to test with test engine.

We create a new class under the test folder under our main folder as DogsRouteTest.

class DogsRouteTest {}

Following is the test case for GET all dogs route.

@Test
fun testGetAllDog() {
withTestApplication({ module() }) {
handleRequest(HttpMethod.Get,"/dogs").apply {
assertEquals(
HttpStatusCode.NotFound,
response.status()
)
}
}
}

We annotate the function with Test and uses the withTestApplication function which is the module function provided by Ktor. We simply pass the url path and http type to handleRequest function and checks if it return http code not found. If we run this test, it’ll pass. We can even try failing the test by expecting different status code.

Similarly for our delete route we can write case as follows

@Test
fun testGetSpecificDog() {
withTestApplication({ module() }) {
handleRequest(HttpMethod.Delete,"/dogs").apply {
assertEquals(
HttpStatusCode.NotFound,
response.status()
)
}
}
}

Similarly we can check for other routes as well.

We’ve tested our APIs via test cases. It is time to test them via Postman.

If we hit the curl request in postman

curl --location --request POST 'http://localhost:8080/dogs' \
--header 'Content-Type: application/json' \
--data-raw '{
"name": "Peter",
"color": "Brown",
"id": 5
}'

We’re getting the response as follows

Dog saved, 201 Created

Similarly we can test our other APIs as well. Hence we see that all our APIs are working correctly. I expect you would test other APIs as well. They should work. 😀

Yeah! So now we are familiar with API development using Ktor framework. Build more features around and play with it.

This was a simple and quick tutorial. Hope you’ll find it helpful in some way.

Full code can be found on github : here under static-apis branch.

Cheers! 🍺

--

--

App Developer (Native & Flutter) | Mentor | Writer | Youtuber @_zaqua | Traveller | Content Author & Course Instructor @Droidcon | Frontend Lead @MahilaMoney