Golang test mocking using dependency injection

You will often have a struct with many dependencies for your main logic. Dependency injection comes in handy if you want to test and mock certain dependencies. I will show you in this article how to apply DI for mocking in test with Golang.

I’ve identified two types of dependency injections:

  • Type injection
  • Interface injection

Type injection is often used when you need to inject a type that is slightly different from how you would use it in production. E.g. a database connector in a testcase needs to connect to the test database with different credentials.

type MainLogic struct {
db DB *sqlx.DB
}
func NewMainLogic(db *sqlx.DB) Foo {
return MainLogic{db: db}
}
testDB, _ := sqlx.Open("postgres", testdbconnectionstring)
foo := NewFoo(testDB)

As you can see it is very simple to inject a different *sqlx.DB type here.

Interface injection is where things become more interesting and where I will go deeper down the rabbit hole.

I came up with a robots.txt parser to showcase DI mocking. Your main logic struct does not accept a specific type in this case, but instead the Roboteer interface. Now you can put in any struct satisfying the Roboteer interface.

type MainLogic struct {
robotsClient Roboteer
}

This is the full code of the robots.txt parser:

To test your main logic with the Roboteer dependency, you don’t really have to mock the entire dependency. You can also feed the FetchRobots an http test server URL and be done with it.

In many cases, this will be enough, but in case you don’t want to make any HTTP calls at all, you can mock the entire FetchRobots methods in a new struct satisfying the Roboteer interface.

With the new MockRobotsClient we can pass multiple mocks to the constructor for each potential FetchRobots call.

Now you see that you can create very extensive mocks for your dependencies using dependency injection. For more complicated interfaces, I created a showcase package called interfacemocker. This package will help you construct mocks for interface methods with single or multiple return values.

Happy testing and mocking!


Golang test mocking using dependency injection was originally published in Everything Full Stack on Medium, where people are continuing the conversation by highlighting and responding to this story.

Senior Backend Engineer

Backend Group

Thank you for your interest!

We will contact you as soon as possible.

Want to Know More?

Oops, something went wrong
Please try again or contact us by email at info@tikalk.com
Thank you for your interest!

We will contact you as soon as possible.

Let's talk

Oops, something went wrong
Please try again or contact us by email at info@tikalk.com