Sling Academy
Home/Golang/Unit Testing with the `testing` Package in Go

Unit Testing with the `testing` Package in Go

Last updated: November 26, 2024

Unit testing is an essential aspect of ensuring that your code works as expected. The Go programming language, with its built-in package named testing, provides support for unit testing and benchmarking. In this article, we will explore how to effectively use this package to write unit tests for your Go applications.

Getting Started with the testing Package

To create a unit test in Go, you start by creating a test file with a _test.go suffix. The file should be placed in the same package as the code you wish to test. Each test function should start with the word Test and take a single argument of type *testing.T.

Example Structure

Let’s say we have a simple Go function in a file called math.go:

// File: math.go
package mathutils

// Add two integers and return the sum
func Add(a int, b int) int {
    return a + b
}

We can write a test for this function in a separate file math_test.go:

// File: math_test.go
package mathutils

import "testing"

func TestAdd(t *testing.T) {
    sum := Add(2, 3)
    expected := 5
    if sum != expected {
        t.Errorf("Add(2, 3) = %d; expected %d", sum, expected)
    }
}

Running the Tests

To run your tests, navigate to the directory containing your test files and run:

go test

This command will automatically compile the test files and execute the tests, displaying results in the console.

Using Table-Driven Tests

For functions with multiple scenarios, it’s often useful to implement table-driven tests for efficiency. Here's an example of a table-driven test:

func TestAddTableDriven(t *testing.T) {
    tests := []struct {
        name     string
        a, b     int
        expected int
    }{
        {"two plus three", 2, 3, 5},
        {"zero added to five", 0, 5, 5},
        {"negative numbers", -1, -1, -2},
    }

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

Conclusion

Unit testing in Go using the testing package is straightforward and powerful, enabling developers to write reliable and performant applications. By following the patterns discussed, such as writing simple test cases and using table-driven tests, you can ensure your functions behave as expected under various conditions.

Next Article: Profiling and Debugging Performance with the `pprof` Package in Go

Previous Article: Debugging Applications with the `log` Package in Go

Series: Working with Core package in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant