A Testify Cheat Sheet for Assertions Mocks and Suites
A testify cheat sheet for Go: the assertions worth knowing, assert against require, mock calls, suite hooks and HTTP helpers, with the one trap each has.

A compact reference for the testify functions that cover most Go tests. Everything on the sheet ran in one test on Go 1.25.6 with testify v1.11.1. Argument order is (t, expected, actual) unless noted, and every assert function has a require twin.
Tested with Go 1.25.6, testify v1.11.1, macOS on Apple Silicon (arm64)
package main
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestCheatSheet(t *testing.T) {
a := assert.New(t)
a.Equal(2, 1+1) // equal, with ObjectsAreEqual semantics
a.NotEqual(1, 2)
a.True(true)
a.Nil((*int)(nil)) // typed nil pointers count as nil
a.NotNil(1)
a.Zero(0)
a.Empty("")
a.Len([]int{1, 2}, 2)
a.Contains("hello", "ell")
a.Subset([]int{1, 2, 3}, []int{2})
a.ElementsMatch([]int{1, 2}, []int{2, 1})
a.Greater(3, 2)
a.GreaterOrEqual(3, 3)
a.InDelta(1.0, 1.0004, 0.001)
a.WithinDuration(time.Unix(0, 0), time.Unix(1, 0), 2*time.Second)
a.Regexp(`^h.+o$`, "hello")
a.JSONEq(`{"a":1,"b":2}`, `{"b":2,"a":1}`)
}
func TestSameVsEqual(t *testing.T) {
x := &struct{ N int }{1}
y := &struct{ N int }{1}
assert.Equal(t, x, y) // pointers compared by ObjectsAreEqual: contents
require.NotSame(t, x, y)
t.Log("Equal compares contents, Same compares identity")
}
func main() {}go test -count=1 -v . 2>&1 | grep -vE '^(=== RUN|=== PAUSE|=== CONT|=== NAME|PASS|ok|FAIL$|FAIL\s|exit status)' | sed -E 's/ \([0-9.]+s\)//; s#^ +[a-z_0-9]+\.go:[0-9]+: # #; s/\x1b\[[0-9;]*m//g; s#/[^[:space:]]*/([a-z_0-9]+\.go)#\1#g; s/[[:space:]]+$//' | grep -vE '^\s*$'--- PASS: TestCheatSheet
Equal compares contents, Same compares identity
--- PASS: TestSameVsEqualAssertions by job
| Job | Function | Compares | Watch out for |
|---|---|---|---|
| Values | Equal, NotEqual | Deep equality, same type | Equal(t, 1, int64(1)) fails |
| Values | EqualValues | After conversion | Hides real type bugs |
| Values | Exactly | Same type and value | Stricter than Equal for numbers |
| Identity | Same, NotSame | Pointer identity | Equal on pointers compares contents |
| Booleans | True, False | A bool | Prints nothing useful on failure |
| Nil | Nil, NotNil | Nil, including typed nils | A nil pointer in an interface counts as nil |
| Zero | Zero, NotZero | The type's zero value | |
| Empty | Empty, NotEmpty | Zero, or length 0 | Works on slices, maps, strings, channels |
| Errors | NoError, Error | Presence | Does not say which error |
| Errors | ErrorIs, ErrorAs | The error chain | Pass a pointer to ErrorAs |
| Errors | EqualError, ErrorContains | The message text | Couples the test to wording |
| Size | Len | Length of slice, map, string, channel | |
| Collections | Contains, NotContains | Substring, element, map key | |
| Collections | Subset, ElementsMatch | Membership, ignoring order | ElementsMatch is the one for unordered results |
| Order | Greater, GreaterOrEqual, Less, LessOrEqual | Ordered values | Same types required |
| Numbers | InDelta, InEpsilon | Within an absolute or relative error | Never Equal for floats |
| Time | WithinDuration | Two times within a delta | Inject a clock instead where possible |
| Text | Regexp, NotRegexp | A pattern against a string | |
| Structured | JSONEq, YAMLEq | Parsed documents | Key order and whitespace ignored |
| Panics | Panics, PanicsWithValue, PanicsWithError, NotPanics | A function's panic | Takes a func() |
| Time passing | Eventually, Never, EventuallyWithT | Polls a condition | Condition runs on another goroutine |
| Files | FileExists, DirExists, NoFileExists | Paths |
The one test that ran them
All eighteen checks in TestCheatSheet passed. Two behaviours are worth stating because they trip people.
assert.Nil((*int)(nil)) passed. A typed nil pointer is treated as nil by testify's isNil, which checks the value's kind and calls IsNil; a plain == nil comparison on an interface holding a typed nil would be false. That is convenient and slightly different from the language rule, so be aware of it when an error interface holds a typed nil.
TestSameVsEqual compares two distinct pointers to structs with equal contents. assert.Equal passes, because ObjectsAreEqual looks at what they point to, and require.NotSame passes, because the addresses differ. The log line Equal compares contents, Same compares identity is the summary.
Assert and require
assert | require | |
|---|---|---|
| On failure | Records it, test continues | Records it, stops the test |
| Mechanism | t.Errorf | t.FailNow |
| Use for | Independent checks on a result | Guards: errors, nil, length |
| From a goroutine | Safe | Not safe: stops only that goroutine |
The long form is in assert versus require.
Mocks
| Task | Code |
|---|---|
| Declare | type M struct{ mock.Mock }, methods call m.Called(args...) |
| Expect | m.On("Method", arg1, arg2).Return(v1, v2) |
| Limit | .Once(), .Twice(), .Times(n), .Maybe() |
| Match | mock.Anything, mock.AnythingOfType("T"), mock.MatchedBy(func(x T) bool {...}) |
| Side effect | .Run(func(args mock.Arguments){...}) |
| Verify | m.AssertExpectations(t), AssertCalled, AssertNotCalled, AssertNumberOfCalls |
| Read return | args.Error(0), args.String(0), args.Int(0), args.Bool(0), args.Get(0) |
The trap: an unexpected call panics, a missing call is only found by AssertExpectations. Details in the mock article.
Suites
| Hook | Runs |
|---|---|
SetupSuite, TearDownSuite | Once per suite |
SetupTest, TearDownTest | Around every test method |
SetupSubTest, TearDownSubTest | Around every s.Run subtest |
BeforeTest, AfterTest | Around each method, with names |
Methods run alphabetically. Start with suite.Run(t, new(S)). See the suite article.
HTTP helpers
assert.HTTPSuccess, HTTPError, HTTPRedirect, HTTPStatusCode, HTTPBodyContains, HTTPBodyNotContains take a handler function, method, URL and url.Values, and call the handler once per assertion. For headers or JSON bodies use httptest; see the HTTP article.
The traps, in one place
Equalneeds matching types: anintand anint64never compare equal.Equalon floats is a coin toss; useInDelta.Containson a map checks keys, not values.Emptyis true for zero values as well as empty collections, soEmpty(t, 0)passes.ElementsMatchcompares as multisets, so duplicates count.Eventuallyruns its condition on another goroutine.assert.New(t)binds thetyou give it; create it inside the subtest.AssertExpectationsmust be called, or a mock's missing calls go unnoticed.mock.Anythingweakens the check to the point of "was it called".suitemethods run in alphabetical order, and fields persist between them.
Habits
- Expected first, actual second.
requirefor the line that makes the next line safe.- Name the case in loops:
assert.Equal(t, want, got, "case %q", name). - Create
assert.New(t)inside the subtest. - Prefer
ErrorIsandLentoErrorandTrue. - Verify mocks every time, because a mock that is never verified cannot fail for a call that never happened.
The release notes live in the testify repository, and the reference is the testify documentation on pkg.go.dev, and the tutorial that explains each family is the assertions article.


