You should Unit Test your API endpoints, it’s easy!

Oliver Mascarenhas
Code Uncomplicated
Published in
2 min readFeb 17, 2022

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!!

Would you rather watch a video instead?

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.

The Server struct

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.

Unit Test for API Endpoint

Defining and Mocking the Service layer

Defining the service as an interface lets us pass in mocked implementations during unit testing.

Mocking the Service Layer

Setting up and unit testing with this approach ensures we test out our configuration from

Endpoint -> Route -> Handler -> Service Layer

References & Links

--

--

Oliver Mascarenhas
Code Uncomplicated

Designing and developing scalable and fault tolerant data pipelines and platforms | https://olivermascarenhas.com/