Assertions: the standard library and the libraries
Go has no assertion function in the standard library. A test compares two values with if and reports with t.Errorf or t.Fatalf, and the testing package prints the file, the line and the message. That is enough for most code, and every library below is a wrapper around it that adds a message or a diff. This page runs the same two failing cases through four ways of writing them, so the choice is made on output and cost rather than on taste.
The standard library
The package under test has two small functions, and the table gives both of them a wrong expectation on purpose.
package calc
import "errors"
// ErrDivideByZero is returned when the denominator is zero.
var ErrDivideByZero = errors.New("divide by zero")
// Divide returns a/b, or ErrDivideByZero.
func Divide(a, b int) (int, error) {
if b == 0 {
return 0, ErrDivideByZero
}
return a / b, nil
}
// Clamp limits v to the range [lo, hi].
func Clamp(v, lo, hi int) int {
if v < lo {
return lo
}
if v > hi {
return hi
}
return v
}
package calc
import "testing"
func TestClampPlain(t *testing.T) {
cases := []struct {
v, want int
}{
{11, 12},
{0, -1},
}
for _, tc := range cases {
if got := Clamp(tc.v, 1, 10); got != tc.want {
t.Errorf("Clamp(%d, 1, 10) = %d, want %d", tc.v, got, tc.want)
}
}
}
go test -trimpath -v -run TestClampPlain ./calc
=== RUN TestClampPlain
plain_test.go:14: Clamp(11, 1, 10) = 10, want 12
plain_test.go:14: Clamp(0, 1, 10) = 1, want -1
--- FAIL: TestClampPlain (0.00s)
FAIL
FAIL example.com/shop/calc 0.006s
FAIL
Both cases were reported, because t.Errorf marks the test failed and returns. t.Fatalf would have ended the test at the first one, which is right when the rest of the test would panic: a nil map, a missing file, a value that is not there. The message is a sentence the author writes, and the numbers come from the format string, so a reader of the log sees the call and both values.
-trimpath is not required, but it makes the output portable: without it a library that reads the call stack prints the absolute path of the file on this machine.
testify
testify is the most used testing library in Go. It has two packages that matter here: assert reports a failure and continues, and require reports it and stops the test. The table is the same, written with assert.Equal:
package calc
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestClampAssert(t *testing.T) {
cases := []struct {
v, want int
}{
{11, 12},
{0, -1},
}
for _, tc := range cases {
assert.Equal(t, tc.want, Clamp(tc.v, 1, 10), "Clamp(%d, 1, 10)", tc.v)
}
}
go test -trimpath -v -run TestClampAssert ./calc
=== RUN TestClampAssert
clamp_test.go:17:
Error Trace: example.com/shop/calc/clamp_test.go:17
Error: Not equal:
expected: 12
actual : 10
Test: TestClampAssert
Messages: Clamp(11, 1, 10)
clamp_test.go:17:
Error Trace: example.com/shop/calc/clamp_test.go:17
Error: Not equal:
expected: -1
actual : 1
Test: TestClampAssert
Messages: Clamp(0, 1, 10)
--- FAIL: TestClampAssert (0.00s)
FAIL
FAIL example.com/shop/calc 0.005s
FAIL
The message is longer and says the same thing: the expected value, the actual one and the sentence the test supplied. The value of the library is not in this case but in the ones where the values are large: assert.Equal walks a slice or a map and prints the first difference, which a hand-written %v of two forty-element slices does not.
The same table with require.Equal stops at the first case:
package calc
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestClampRequire(t *testing.T) {
cases := []struct {
v, want int
}{
{11, 12},
{0, -1},
}
for _, tc := range cases {
require.Equal(t, tc.want, Clamp(tc.v, 1, 10), "Clamp(%d, 1, 10)", tc.v)
}
}
go test -trimpath -v -run TestClampRequire ./calc
=== RUN TestClampRequire
clamp_require_test.go:17:
Error Trace: example.com/shop/calc/clamp_require_test.go:17
Error: Not equal:
expected: 12
actual : 10
Test: TestClampRequire
Messages: Clamp(11, 1, 10)
--- FAIL: TestClampRequire (0.00s)
FAIL
FAIL example.com/shop/calc 0.005s
FAIL
One case, not two: require calls t.FailNow, which ends the goroutine of the test. Use require for a precondition and assert for the claims that follow, and a failure will not be followed by a nil pointer panic three lines later.
go-cmp
go-cmp does one thing: it compares two values of the same type and prints a diff. The direction is cmp.Diff(want, got), and the convention is a -want +got header so a reader knows which side is which.
package cmpdemo
// Server is one process the service starts.
type Server struct {
Name string
Port int
Tags []string
}
// Servers returns the configured servers.
func Servers() []Server {
return []Server{
{Name: "api", Port: 8080, Tags: []string{"http", "json"}},
{Name: "jobs", Port: 9090, Tags: []string{"worker"}},
}
}
package cmpdemo
import (
"testing"
"github.com/google/go-cmp/cmp"
)
func TestServers(t *testing.T) {
want := []Server{
{Name: "api", Port: 8080, Tags: []string{"http", "json"}},
{Name: "jobs", Port: 9091, Tags: []string{"worker"}},
}
if diff := cmp.Diff(want, Servers()); diff != "" {
t.Errorf("Servers() mismatch (-want +got):\n%s", diff)
}
}
go test -trimpath -v -run TestServers ./cmpdemo
=== RUN TestServers
demo_test.go:15: Servers() mismatch (-want +got):
[]cmpdemo.Server{
{Name: "api", Port: 8080, Tags: {"http", "json"}},
{
Name: "jobs",
- Port: 9091,
+ Port: 9090,
Tags: {"worker"},
},
}
--- FAIL: TestServers (0.00s)
FAIL
FAIL example.com/shop/cmpdemo 0.007s
FAIL
One line differs and the diff points at it inside a two-element slice of structs. The types are printed because the diff is also a description of the value. go-cmp panics on a type with unexported fields unless it is given an option such as cmp.AllowUnexported, which is a deliberate restriction: comparing a value that hides state is a decision, not a default. For a single number or a string, cmp.Diff is more machinery than if got != want.
is
is is the small one: one function returns a value whose methods check and stop the test, and each failure names the file and the line of the check. Its messages are coloured on a terminal, and NO_COLOR=1 turns that off, which is what a log should use.
package isdemo
// add returns the sum of two integers.
func add(a, b int) int {
return a + b
}
package isdemo
import (
"testing"
"github.com/matryer/is"
)
func TestAdd(t *testing.T) {
is := is.New(t)
is.Equal(add(2, 2), 4)
is.Equal(add(2, 2), 5)
}
NO_COLOR=1 go test -v -run TestAdd ./isdemo
=== RUN TestAdd
is_test.go:12: 4 != 5
--- FAIL: TestAdd (0.00s)
FAIL
FAIL example.com/shop/isdemo 0.004s
FAIL
The failure is one line: the values and the comparison. There is no expected and actual, because is.Equal compares in the order the arguments are written and does not know which one is the expectation. For a small test that is pleasant; for a value with ten fields it tells a reader much less than the diff above.
Which one to pick
The costs below are counted in this module after go mod tidy: the modules that appear in go list -m all, the main module included, and the lines of go.sum.
| Way | Modules | go.sum | What it adds | Pick it when |
|---|---|---|---|---|
| testing | 1 | 0 | Nothing but the language: if and a message | Always a valid answer; required for library code with no dependencies |
| testify | 5 | 8 | assert, require, a mock package, a suite runner | The team already knows it, or a large value needs a readable failure |
| go-cmp | 2 | 2 | A structural diff of two values | Comparing structs, slices and maps, especially in table tests |
| is | 2 | 2 | One-line failures that stop the test | A small project that wants shorter tests and no diff |
Two rules save an argument. Do not mix two assertion styles in one package: a reader who sees if got != want in one file and assert.Equal in the next has to switch habits for no reason. And a library that other people import should keep its tests on the standard library, so its go.mod does not grow for everyone who builds it: test dependencies are module dependencies in Go, and there is no dev-dependency section.
The next page, httptest, fakes and mocks, takes the same question to the interfaces of a service. The lessons behind this one are go test and test files and testify and the libraries around it.
The code on this page was run with go 1.26.10, testify 1.12.1, go-cmp 0.7.0 and is 1.4.1 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev