Search⌘ K
AI Features

Utilizing Go's Testing Framework

Explore Go's testing framework to create reliable unit tests. Understand how to write basic tests, implement table-driven tests for multiple cases, and use interfaces to create fakes that avoid external dependencies. Gain insight into testing best practices and popular third-party tools for effective Go testing.

Testing is one of the most important and least loved parts of any language. Testing provides a developer with the knowledge that something works as expected. Most developers cannot count the times that writing unit tests has proven that a function or method did not work the way they expected. This saved countless hours of debugging.

To this end, tests need to have the following attributes:

  • Easy to write

  • Fast to execute

  • Simple to refactor

  • Effortless to understand

To satisfy these needs, Go tackles tests by doing the following:

  • Breaking tests into their own files.

  • Providing a simple testing package.

  • Using a testing methodology called table-driven tests (TDTs).

In this lesson, we will cover how to write basic tests, Go's standard TDT methodology, creating fakes with interfaces, and some third-party packages that are popular, but we don't necessarily recommend.

Creating a basic test file

Go tests are contained in package files with a _test.go suffix. These files have the same package name, and you can include as many test files as needed. The usual rule is to write a test file per package file you want to test so that there is a 1:1 association for clarity.

Each test in a test file is a function whose name is prefixed with Test and has a single argument, t *testing.T, with no returns. This is how it looks:

Go (1.18.2)
func TestFuncName(t *testing.T) {
}

t is passed by the go test command and provides the necessary utilities for our tests. The primary methods used are listed here:

  • t.Error() ...