Contents

Testing in Go

Syntax

Testing is a critical part of software development, ensuring that your code functions correctly and efficiently. Go provides built-in support for writing tests, including table-driven tests and benchmarks, as well as tools for measuring test coverage. Let’s explore these features and see how they can help you maintain high-quality Go code.

Writing Tests

Go uses a simple approach to testing through its testing package. Test files should have a _test.go suffix and test functions should start with Test.

Basic Test Example

Here’s a basic example of a test in Go:

				
					// mathutil.go
package mathutil

// Add adds two integers and returns the result.
func Add(a, b int) int {
    return a + b
}
				
			
				
					// mathutil_test.go
package mathutil

import "testing"

// TestAdd tests the Add function.
func TestAdd(t *testing.T) {
    result := Add(2, 3)
    expected := 5
    if result != expected {
        t.Errorf("Add(2, 3) = %d; want %d", result, expected)
    }
}

				
			

To run the tests, use the command:

				
					go test
				
			

Table-Driven Tests

Table-driven tests are a pattern in Go for testing multiple cases with different inputs and expected outputs. This approach makes it easy to manage multiple test scenarios in a concise format.

Table-Driven Test Example

Let’s expand on the Add function with a table-driven test:

				
					// mathutil_test.go
package mathutil

import "testing"

// TestAdd tests the Add function using a table-driven approach.
func TestAdd(t *testing.T) {
    tests := []struct {
        name     string
        a, b     int
        expected int
    }{
        {"Add positive numbers", 2, 3, 5},
        {"Add zero", 0, 5, 5},
        {"Add negative numbers", -1, -2, -3},
    }

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

				
			

Benchmarking

Benchmarking is used to measure the performance of your code. Go’s testing framework supports benchmarks using functions that start with Benchmark.

Benchmark Example

Here’s how you can write a benchmark for the Add function:

				
					// mathutil_test.go
package mathutil

import "testing"

// BenchmarkAdd measures the performance of the Add function.
func BenchmarkAdd(b *testing.B) {
    for i := 0; i < b.N; i++ {
        Add(2, 3)
    }
}
				
			

Run benchmarks with the command:

				
					go test -bench=.
				
			

Coverage

Coverage analysis helps determine which parts of your code are exercised by tests. Go provides a way to measure test coverage with the -cover flag.

Checking Test Coverage

To check coverage, use:

				
					go test -cover
				
			

For a detailed report, use:

				
					go test -coverprofile=coverage.out
go tool cover -html=coverage.out