Use assert when you want tests to continue after a failure:
funcTestUser(t*testing.T) {
user:=GetUser(123)
// All three checks run, even if the first failsassert.NotNil(t, user)
assert.Equal(t, "Alice", user.Name)
assert.Equal(t, 25, user.Age)
}
Use require when subsequent checks depend on earlier ones:
import"github.com/go-openapi/testify/v2/require"funcTestUser(t*testing.T) {
user:=GetUser(123)
// Stop immediately if user is nil (prevents panic on next line)require.NotNil(t, user)
// Only runs if user is not nilassert.Equal(t, "Alice", user.Name)
}
Rule of thumb: Use require for preconditions, assert for actual checks.
funcTestCollections(t*testing.T) {
list:= []string{"apple", "banana", "cherry"}
// Check if collection contains an elementassert.Contains(t, list, "banana")
assert.NotContains(t, list, "orange")
// Check lengthassert.Len(t, list, 3)
// Check if emptyassert.NotEmpty(t, list)
assert.Empty(t, []string{})
// Check if all elements match (order doesn't matter)assert.ElementsMatch(t, []int{3, 1, 2}, []int{1, 2, 3})
}
Errors
funcTestErrors(t*testing.T) {
// Check if function returns an errorerr:=DoSomething()
assert.Error(t, err)
// Check if function succeedserr = DoSomethingElse()
assert.NoError(t, err)
// Check specific error messageerr = Divide(10, 0)
assert.EqualError(t, err, "division by zero")
// Check if error contains textassert.ErrorContains(t, err, "division")
// Check error type with errors.Isassert.ErrorIs(t, err, ErrDivisionByZero)
}
funcTestFormatted(t*testing.T) {
// Add custom failure message with formattingassert.Equalf(t, 42, result, "expected answer to be %d", 42)
require.NotNilf(t, user, "user %d should exist", userID)
}
3. Forward Methods (Cleaner Syntax)
funcTestForward(t*testing.T) {
a:=assert.New(t)
r:=require.New(t)
// No need to pass 't' each timea.Equal(42, result)
a.NotEmpty(list)
r.NotNil(user)
r.NoError(err)
}
4. Forward Methods with Formatting
funcTestForwardFormatted(t*testing.T) {
a:=assert.New(t)
a.Equalf(42, result, "expected answer to be %d", 42)
a.Lenf(list, 3, "expected %d items", 3)
}
Recommendation: Use package-level functions for simple tests, forward methods for tests with many assertions.
Table-Driven Tests
The idiomatic Go pattern for testing multiple cases should be:
funcTestPanics(t*testing.T) {
// Function should panicassert.Panics(t, func() {
Divide(10, 0)
})
// Function should NOT panicassert.NotPanics(t, func() {
Divide(10, 2)
})
// Function should panic with specific valueassert.PanicsWithValue(t, "division by zero", func() {
Divide(10, 0)
})
}
funcassertUserValid(t*testing.T, user*User) {
t.Helper() // Mark as helper for better error messagesassert.NotNil(t, user)
assert.NotEmpty(t, user.Name)
assert.Greater(t, user.Age, 0)
}
funcTestUsers(t*testing.T) {
user:=GetUser(123)
assertUserValid(t, user) // Failures point to this line, not inside helper}
Note: Without the enable/yaml import, YAML assertions will panic with a helpful message.
Colorized Output (Optional)
Testify can colorize test failure output for better readability. This is an opt-in feature.
Enabling Colors
import (
"testing""github.com/go-openapi/testify/v2/assert"_"github.com/go-openapi/testify/enable/colors/v2"// Enable colorized output)
funcTestExample(t*testing.T) {
assert.Equal(t, "expected", "actual") // Failure will be colorized}
Activation
Colors are activated via command line flag or environment variable:
# Via flaggo test -v -testify.colorized ./...
# Via environment variableTESTIFY_COLORIZED=true go test -v ./...
Themes
Two themes are available for different terminal backgrounds:
# Dark theme (default) - bright colors for dark terminalsgo test -v -testify.colorized ./...
# Light theme - normal colors for light terminalsgo test -v -testify.colorized -testify.theme=light ./...
# Or via environmentTESTIFY_COLORIZED=true TESTIFY_THEME=light go test -v ./...
CI Environments
By default, colorization is disabled when output is not a terminal. To force colors in CI environments that support ANSI codes:
TESTIFY_COLORIZED=true TESTIFY_COLORIZED_NOTTY=true go test -v ./...
What Gets Colorized
Expected values in assertion failures (green)
Actual values in assertion failures (red)
Diff output:
Deleted lines (red)
Inserted lines (yellow)
Context lines (green)
Note: Without the enable/colors import, output remains uncolored (no panic, just no colors).
Best Practices
Use require for preconditions - Stop test immediately if setup fails
Use assert for actual checks - See all failures in one test run
Add custom messages for complex checks - Use formatted variants when assertion failure needs context
Prefer table-driven tests - Test multiple cases systematically
Use forward methods for many assertions - Reduces repetition in long tests
Keep tests focused - One logical concept per test function
Use subtests for related scenarios - Group related checks with t.Run()
Mark helpers with t.Helper() - Get better error locations