You should Unit Test your API endpoints, it’s easy!
An uncomplicated guide to unit test RESTful API endpoints in Go
Continuing to improve on the foundation setup in “Building APIs in Go beyond Hello World” we’ll look at an approach for unit testing API endpoints.
It’s going to involve a bit of refactoring of the base project to make the code unit test friendly, however it should be intuitive to follow along.
TL;DR
Source Code: https://github.com/oliversavio/youtube-vid-code/tree/unit-test/go-api-starter
Watch the video instead of reading?
Bonus: I’ve added some funky tunes!!
Encapsulate out the Server creation
Create a struct to hold the fiber application, this can also hold the services and act as a dependency injection mechanism.
Creating and testing the Server
Now, in the unit tests, we can create an instance of the server and provide it the necessary mock service implementations. As you can see from the example in the code, fiber gives us the ability to call the “Test” method, which takes in a http request and gives back a response. The code snippet below is a slightly modified version of the examples provided by fiber.
Defining and Mocking the Service layer
Defining the service as an interface lets us pass in mocked implementations during unit testing.
Setting up and unit testing with this approach ensures we test out our configuration from
Endpoint -> Route -> Handler -> Service Layer
References & Links
- GoFiber examples
https://github.com/gofiber/recipes - Part 1: Building APIs in Go beyond Hello World
https://medium.com/code-uncomplicated/building-apis-in-go-beyond-hello-world-5d501d6403de - Part 3: How to set up API monitoring with Prometheus & Grafana
https://www.youtube.com/watch?v=pP2DKCKR4CQ - Source Code
https://github.com/oliversavio/youtube-vid-code/tree/unit-test/go-api-starter