Learn Go Β· 17/18

Testing and Benchmarking

8 min read

Testing and Benchmarking in Go πŸ§ͺ

Welcome, intrepid Go developer! You've learned how to build things, and now it's time to learn how to make sure they don't fall apart. Testing in software development is like being a meticulous chef who tastes their own cooking before serving it to customers. You want to catch any issues before they reach the user. In Go, testing is a first-class citizen, meaning the language and its tooling are designed to make testing a natural part of your workflow.

So, grab your lab coat πŸ§‘β€πŸ”¬, and let's dive into the world of Go testing and benchmarking!


1. Writing Your First Unit Test (testing package) πŸ”¬

The Problem: You've written a brilliant function, say, one that adds two numbers. It looks perfect. But is it? What if someone passes in a negative number? What if they pass in zero? What if they pass in the largest possible integer and it overflows? Without a systematic way to check these cases, you're just hoping for the best. This is where unit tests come in. They test the smallest "units" of your code in isolation.

The Solution: Go's built-in testing package provides all the tools you need to write and run unit tests.

Getting Started:

To write a test in Go, you create a new file ending in _test.go. This is a convention that Go's tooling understands.

Let's imagine you have a simple calculator.go file:

go
// calculator.go
package calculator

func Add(a, b int) int {
    return a + b
}

Now, let's write a test for our Add function. We'll create a calculator_test.go file in the same directory.

go
// calculator_test.go
package calculator

import "testing"

func TestAdd(t *testing.T) {
    got := Add(2, 3)
    want := 5

    if got != want {
        t.Errorf("Add(2, 3) = %d; want %d", got, want)
    }
}

Breaking it Down:

  • package calculator: Test files are in the same package as the code they are testing.
  • import "testing": We import the testing package, which gives us the tools for our test.
  • func TestAdd(t *testing.T): Test functions in Go must start with the word Test followed by a name that starts with a capital letter. They always take one argument: a pointer to a testing.T type. Think of t as your testing toolkit, allowing you to report errors, log information, and more.
  • t.Errorf(...): This is how you signal a test failure. When t.Errorf is called, the test is marked as failed, but it continues to execute. If you want to stop the test immediately upon failure, you can use t.Fatalf.

Running Your Test:

To run your tests, open your terminal in the calculator directory and run:

sh
go test

If everything is correct, you'll see a reassuring PASS. If not, Go will report the failure with the error message you provided.

Fun Fact ✨: The go test command is incredibly powerful. It automatically finds all _test.go files in your package, compiles them, and runs the test functions. You can also get more detailed output by using the -v (verbose) flag: go test -v.


2. Table-Driven Tests: The Go Standard πŸ“Š

The Problem: Your Add function is simple. But what about a more complex function? Writing a separate Test... function for every single scenario (positive numbers, negative numbers, zero) would be tedious and repetitive. Your test file would become bloated and hard to maintain.

The Solution: Table-driven tests are a common pattern in Go for testing multiple scenarios with the same test logic. You define a "table" (a slice of structs) where each entry represents a test case with its inputs and expected output.

Let's refactor our TestAdd function to use this approach.

go
// calculator_test.go
package calculator

import "testing"

func TestAdd(t *testing.T) {
    testCases := []struct {
        name string
        a, b int
        want int
    }{
        {name: "Positive numbers", a: 2, b: 3, want: 5},
        {name: "Negative numbers", a: -2, b: -3, want: -5},
        {name: "One positive, one negative", a: -2, b: 3, want: 1},
        {name: "Adding zero", a: 5, b: 0, want: 5},
    }

    for _, tc := range testCases {
        t.Run(tc.name, func(t *testing.T) {
            got := Add(tc.a, tc.b)
            if got != tc.want {
                t.Errorf("Add(%d, %d) = %d; want %d", tc.a, tc.b, got, tc.want)
            }
        })
    }
}

Breaking it Down:

  • testCases := []struct{...}: We declare a slice of anonymous structs. Each struct holds the inputs (a, b), the expected output (want), and a descriptive name for the test case.
  • for _, tc := range testCases: We loop through our testCases.
  • t.Run(tc.name, func(t *testing.T) {...}): This is the magic! t.Run creates a subtest for each test case. This is great because if one case fails, the others will still run, and the test output will clearly show which named case failed.

Why is this the industry standard?

  • Clarity: It's easy to see all the different scenarios being tested.
  • Maintainability: Adding new test cases is as simple as adding a new struct to the slice.
  • Thoroughness: It encourages you to think about and cover a wide range of inputs.

3. Mocking Dependencies for Effective Testing 🎭

The Problem: Your code often depends on other things: a database, a network service, the file system. When you're unit testing a piece of code, you want to test it in isolation. If your test fails, you want to know it's because your code is broken, not because the database is down or the network is flaky.

The Solution: Mocking! Mocking is the practice of creating "fake" versions of these dependencies that you can control in your tests. These fake versions are called "mocks" or "stubs."

Imagine you have a function that gets user data from a database.

go
// user/user.go
package user

type User struct {
    ID   int
    Name string
}

type Datastore interface {
    GetUser(id int) (*User, error)
}

func GetUserName(db Datastore, id int) (string, error) {
    user, err := db.GetUser(id)
    if err != nil {
        return "", err
    }
    return user.Name, nil
}

Notice we're using an interface (Datastore). This is key to making our code testable. We're not tied to a specific database implementation.

Now, in our test, we can create a mock Datastore.

go
// user/user_test.go
package user

import "testing"

type MockDatastore struct{}

func (m *MockDatastore) GetUser(id int) (*User, error) {
    // In our mock, we can return whatever we want for the test.
    if id == 1 {
        return &User{ID: 1, Name: "Alice"}, nil
    }
    return nil, nil // Or an error for other cases
}

func TestGetUserName(t *testing.T) {
    mockDB := &MockDatastore{}
    name, err := GetUserName(mockDB, 1)

    if err != nil {
        t.Fatalf("unexpected error: %v", err)
    }

    want := "Alice"
    if name != want {
        t.Errorf("GetUserName(1) = %s; want %s", name, want)
    }
}

Breaking it Down:

  • type MockDatastore struct{}: We create a struct that will act as our fake database.
  • func (m *MockDatastore) GetUser(...): We implement the GetUser method on our MockDatastore. Now, MockDatastore satisfies the Datastore interface.
  • Controlling the Outcome: Inside our mock GetUser, we can return whatever data we need for our test. We can simulate a successful user lookup, a user not being found, or even a database error.

Under the Hood: This works because of Go's implicit interfaces. As long as our MockDatastore has all the methods required by the Datastore interface, we can use it anywhere a Datastore is expected. This is a powerful concept for writing loosely coupled and testable code.


4. Writing and Running Performance Benchmarks ⏱️

The Problem: Your code works, which is great. But is it fast? Sometimes, especially for performance-critical applications, you need to measure the speed of your code and identify bottlenecks.

The Solution: Go's testing package also has built-in support for benchmarking. Benchmarks measure how long a piece of code takes to run and how much memory it allocates.

Let's say we have a function that concatenates strings. We want to see how fast it is.

go
// concat/concat.go
package concat

func ConcatStrings(s []string) string {
    var result string
    for _, v := range s {
        result += v
    }
    return result
}

Now, let's write a benchmark for it in concat/concat_test.go.

go
// concat/concat_test.go
package concat

import "testing"

var testStrings = []string{"a", "b", "c", "d", "e"}

func BenchmarkConcatStrings(b *testing.B) {
    for i := 0; i < b.N; i++ {
        ConcatStrings(testStrings)
    }
}

Breaking it Down:

  • func BenchmarkConcatStrings(b *testing.B): Benchmark functions start with Benchmark, are followed by a capitalized name, and take a pointer to a testing.B.
  • b.N: This is the crucial part. The benchmarking tool will automatically determine how many times to run the loop (b.N) to get a statistically significant measurement. You don't set b.N yourself; you just write your loop to run b.N times.

Running Your Benchmark:

To run benchmarks, you use the -bench flag with go test. The . tells it to run all benchmarks in the package.

sh
go test -bench=.

The output will look something like this:

apache
goos: darwin
goarch: amd64
pkg: awesome-project/concat
BenchmarkConcatStrings-8   10000000   112.5 ns/op
PASS
ok      awesome-project/concat   1.234s
  • BenchmarkConcatStrings-8: The name of the benchmark and the number of CPUs used (GOMAXPROCS).
  • 10000000: The number of times the loop ran (b.N).
  • 112.5 ns/op: The average time it took for one operation (one call to ConcatStrings). This is the number you care about!

Interesting Tidbit 🧐: Benchmarking can sometimes lead to surprising discoveries. For string concatenation in a loop, using the += operator is often less efficient than using the strings.Builder type from the standard library because it creates a new string in memory on every iteration. Writing a benchmark can prove this and help you justify a code change.


Further Reading πŸ“š

Challenge

You are tasked with testing a function, GetUserFullName, which depends on an external Datastore. Your goal is to write a complete and robust test suite for this function in the main_test.go file.

Requirements:

  1. Create a Mock: Implement a struct named MockDatastore that satisfies the Datastore interface. This mock must be configurable to return specific values or errors for testing different scenarios.

  2. Write a Table-Driven Test: Create a test function named TestGetUserFullName. This function must use a table-driven approach to test the GetUserFullName function with multiple cases. Use t.Run to create a subtest for each case. Your test table must cover at least these three scenarios:

    • A successful retrieval where both first and last names are found.
    • A failure scenario where GetFirstName returns an error.
    • A failure scenario where GetLastName returns an error.
  3. Write a Benchmark: Create a benchmark function named BenchmarkGetUserFullName to measure the performance of the GetUserFullName function. Use your MockDatastore to provide data for the benchmark loop.

Expected result

Your main_test.go file should contain the following implementations:

  1. A MockDatastore struct definition. It should have fields to store the desired first name, last name, and potential errors to be returned by its methods.

  2. Implementations of the GetFirstName(userID int) (string, error) and GetLastName(userID int) (string, error) methods for the *MockDatastore type. These methods should return the values stored in the mock's fields.

  3. A TestGetUserFullName(t *testing.T) function that defines a slice of test case structs. Each struct should include a descriptive name, input arguments (like the userID and mock data), the expected full name string, and whether an error is expected.

  4. Inside TestGetUserFullName, a for loop that iterates over the test cases, calling t.Run for each case to create a subtest.

  5. Within each subtest, the GetUserFullName function should be called with a configured MockDatastore instance. The subtest must verify that the returned full name and error match the expected values for that case, using t.Errorf or t.Fatalf to report discrepancies.

  6. A BenchmarkGetUserFullName(b *testing.B) function. This function should initialize a MockDatastore for a successful scenario. It must contain a for loop that runs from i := 0 to b.N, calling GetUserFullName on each iteration to properly measure its performance.

go

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.