...

/

Utilizing Go's Testing Framework

Utilizing Go's Testing Framework

Understand Go's testing framework and how it's utilized to check whether our codes function.

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:

Press + to interact
func TestFuncName(t *testing.T) {
}

t ...