Mocking External Dependencies in Go

Shailesh Suryawanshi
2 min readAug 9, 2020

Hello Gophers, Most of us who tried unit testing must have stuck at external dependencies. That external dependency is maybe of message broker, database, external service APIs, or any other functionality. We wish to decouple our code from the external dependencies and test just what is ours. This post tries to address this scenario.

Let's say we have this piece of code consuming external package “external”

And our External dependency code looks something like this.

As you must have guessed, we would like to Mock this dependency function. Golang’s Interface facilitates exactly that. Let me show you how?

Let's create an interface that encapsulates DependencyFunction from external dependency.

With the interface defined let’s add struct implementing that interface. All the communication to the external dependency will be later carried out by this struct.

With all things in place, We will need a factory method to get us the implementer (struct) of the external dependency interface.

Let's update our main function so that it consumes the factory.

With this, all the communication to the external library will be done through the encapsulated interface. Now, whenever we want to mock the behavior of the external dependency all we will need to do is to create a mock struct implementing external dependency interface.

With this, the factory method also needs to be updated. For the factory to decide which struct to return we will pass an environment parameter. The environment variable can be injected through context, command-line flags, or through dependency injection.

And here the one last thing is remaining, we will need to update the factory method’s consumer. The consumer will need to pass the environment variable. For simplicity, we are sending command-line flags to our application.

Here we are all done. Whenever an environment variable test is passed to the factory method, it will always return the mock struct to its consumer.

Note:- We can always use mocking frameworks like testify or goMock for the function mocks. Mocking frameworks are out of the scope of this post. I wanted to introduce you to the idea of mocking external dependencies in Go.

The complete code of the post can be found at https://github.com/ShaileshSurya/go-external-mocking.git

--

--