Ktor as Mock HTTP Server For Integration Testing (JUnit5, Kotlin)

Photo by Nicolas Thomas on Unsplash

This tutorial demonstrates an easy replacement of the mock-server. If you write in Kotlin and need to validate endpoint calls correctness, look no further! You can check the mock-server tutorial if you need a monster

Let’s model service A which talks to service B over HTTP. First is ours, and service B belongs to a well-funded government company which has no staging or dev environments, production only. Oh, sad.

You can use mocks to verify connection works fine. This is ok in 81% of cases, but sometimes you can’t inject mocks (legacy code creates it on the fly?).

Our application will call some endpoint and we will write a test for it

For the test to work we create a Ktor server and listen for the endpoint calls.

To begin, we implement server start up on a random port, with Jackson serialization and listening for a endpoint.

Every call on endpoint populates collection which we will use in the test to verify it worked

Ta-daam!

That is it! We have a pretty flexible endpoint capturing facility and can enjoy green tests. Here, enjoy:

😂

You can find a complete working example here