greatcodeNavigate back to the homepage

Unit testing in Go

Mike Christensen
August 26th, 2020 · 2 min read

Why Write Unit Tests?

Unit tests validate that each of the component parts of your application are functioning as expected. They are the most granular level of test, and test small chunks of code in isolation. They are often considered cheap: they don’t take a long time to write and should execute quickly.

Testing Pyramid

Since unit tests are cheap, it makes sense that they are used to catch and test the error boundaries of your function under test. Indeed, ideally you should have a unit test for each possible code path through your function (the extent to which this is true is called ”coverage”).

Martin Fowler has previously made a distinction between solitary and sociable unit tests.

Solitary vs. Sociable Unit Tests

Like all things in the domain of software testing, the line can be blurry here. In general, err on the side of solitary testing. The more a unit test is sociable, the more it looks like an integration test. If it is difficult to test a specific unit of code in a solitary fashion, this may hint at an architectural flaw in your code: the other units with which your code interacts may need to be injected as dependencies, so that they can be mocked.

How to Test in Isolation

In order to isolate a unit of code under test, its dependencies must be substituted for a test double. To facilitate the substitution, the dependencies must be provided to the function under test as an argument or as a property on the receiving struct, for example via dependency injection.

Test doubles come in the flavours of stubs, fakes, spies and mocks, in order of increasing complexity.


Stubs are the most basic form of test double, which simply return some predefined output regardless of input. They are typically written for one particular test, as they have hardcoded expectations and assumptions.

Here’s a simple example in Go:

1// foobar.go
3type Fooer interface {
4 Foo() int
7func Bar(foo Fooer, i int) int {
8 return foo.Foo() * i
11// foobar_test.go
13type FooStub struct{}
15func (f *FooStub) Foo() int {
16 return 5;
19func TestBar(t *testing.T) {
20 stub := &FooStub{}
21 got := Bar(stub, 2)
22 expected := 10
23 if got != expected {
24 t.Fatalf("%d != %d", got, expected)
25 }


In more complex scenarios, or in situations where you need to substitute the same dependency in multiple tests, mocks come in handy. Mocks allow you to configure different expectations on inputs and set different return values accordingly.

I typically use mocks wherever a stub is not sufficient, as they provide all the functionality of fakes and spies.


GoMock is a handy tool that makes it dead easy to generate mock code for your interfaces. Simply execute the mockgen binary providing your source file as input:

1mockgen -source=foobar.go

Then you can set expectations and return values with a simple API:

1func TestBar(t *testing.T) {
2 ctrl := gomock.NewController(t)
3 defer ctrl.Finish()
4 m := NewMockFooer(ctrl)
5 m.EXPECT().Bar(gomock.Eq(2)).Return(10)
6 Bar(m, 2)


If you need to mock a database connection, sqlmock does an excellent job of allowing you to set expectations to match SQL queries. It implements sql/driver, allowing you to substitute it wherever you use database/sql.

1// foobar.go
3func Foo(db *sql.DB, a, b int) error {
4 tx, err := db.Begin()
5 if err != nil {
6 return err
7 }
8 defer tx.Rollback()
10 _, err = tx.Exec("INSERT INTO some_table (a, b) VALUES (?, ?)", a, b)
11 if err != nil {
12 return err
13 }
14 err = tx.Commit()
15 return err
18// foobar_test.go
20func TestFoo(t *testing.T) {
21 db, mock, err := sqlmock.New()
22 if err != nil {
23 t.Fatalf("failed to open mocked db connection: %s", err)
24 }
25 defer db.Close()
27 mock.ExpectBegin()
28 mock.ExpectExec("INSERT INTO some_table").
29 WithArgs(2, 3).
30 WillReturnResult(sqlmock.NewResult(1, 1))
31 mock.ExpectCommit()
33 err = Foo(db, 2, 3)
34 if err != nil {
35 t.Fatalf("Foo returned unexpected error: %s", err)
36 }


Unit tests are an essential part of building robust, reliable and maintainable software. I typically have the unit tests automatically run whenever I change a file in my codebase, so I can instantly see when I break something.

Don’t make the mistake of thinking the upfront cost of writing tests outweighs their benefit. The main cost relating to software comes after it has been written, when it must be maintained. Over time, unit tests will save you and your company thousands of developer hours.

How do you write unit tests in Go? Hit me up on Twitter!

More articles from Christensen Codes

Dependency Injection in Go

How to write modular, maintainable and testable Go applications.

August 25th, 2020 · 2 min read

SQL Database Migrations in Go

How to safely manage schema migrations in your Go microservice.

August 24th, 2020 · 2 min read
© 2020–2022 Christensen Codes
Link to $ to $ to $