Testify is a comprehensive testing toolkit for Go that provides three primary packages for different testing needs: assert for flexible assertions, require for strict assertions, mock for creating mock objects, and suite for building structured test suites with setup/teardown capabilities.
go get github.com/stretchr/testify@v1.11.1github.com/stretchr/testifyimport (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/suite"
)import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestSomething(t *testing.T) {
// Basic assertions
assert.Equal(t, 123, 123, "they should be equal")
assert.NotNil(t, obj, "object shouldn't be nil")
assert.True(t, condition, "condition should be true")
// Using Assertions wrapper for cleaner syntax
a := assert.New(t)
a.Equal(expected, actual)
a.NoError(err)
}import (
"testing"
"github.com/stretchr/testify/require"
)
func TestCritical(t *testing.T) {
// require stops test execution on first failure
require.NoError(t, err)
require.NotNil(t, obj)
// Code below only runs if above assertions pass
result := obj.DoSomething()
require.Equal(t, expected, result)
}import (
"testing"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/assert"
)
// Define mock
type MockDB struct {
mock.Mock
}
func (m *MockDB) Get(key string) (string, error) {
args := m.Called(key)
return args.String(0), args.Error(1)
}
func TestWithMock(t *testing.T) {
mockDB := new(MockDB)
// Set expectations
mockDB.On("Get", "user:1").Return("John Doe", nil)
// Use mock
name, err := mockDB.Get("user:1")
// Verify
assert.NoError(t, err)
assert.Equal(t, "John Doe", name)
mockDB.AssertExpectations(t)
}import (
"testing"
"github.com/stretchr/testify/suite"
)
type MyTestSuite struct {
suite.Suite
db *Database
}
func (s *MyTestSuite) SetupSuite() {
// Runs once before all tests
s.db = OpenDatabase()
}
func (s *MyTestSuite) TearDownSuite() {
// Runs once after all tests
s.db.Close()
}
func (s *MyTestSuite) TestExample() {
s.Equal(123, 123)
s.NoError(err)
}
func TestMyTestSuite(t *testing.T) {
suite.Run(t, new(MyTestSuite))
}The assert package provides 100+ assertion functions for flexible testing. All assertions return a boolean indicating success/failure but allow test execution to continue.
// Core equality assertions
func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
// Nil assertions
func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool
func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool
// Error assertions
func Error(t TestingT, err error, msgAndArgs ...interface{}) bool
func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool
func ErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool
func ErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interface{}) bool
// Collection assertions
func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool
func ElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) bool
func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) boolThe require package provides identical API to assert but stops test execution immediately on first failure. All assertion functions call t.FailNow() instead of t.Fail().
// Same API as assert, but stops execution on failure
func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool
func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) boolRequire Package - Complete API
Create and verify mock objects with flexible argument matching and expectation tracking.
// Mock is the core mock object
type Mock struct {
// contains filtered or unexported fields
}
// Set up expectations
func (m *Mock) On(methodName string, arguments ...interface{}) *Call
// Record method calls
func (m *Mock) MethodCalled(methodName string, arguments ...interface{}) Arguments
// Verify expectations
func (m *Mock) AssertExpectations(t TestingT) bool
func (m *Mock) AssertCalled(t TestingT, methodName string, arguments ...interface{}) bool
func (m *Mock) AssertNumberOfCalls(t TestingT, methodName string, expectedCalls int) bool
// Call represents a method call expectation
type Call struct {
Parent *Mock
Method string
Arguments Arguments
ReturnArguments Arguments
}
// Configure call expectations
func (c *Call) Return(returnArguments ...interface{}) *Call
func (c *Call) Once() *Call
func (c *Call) Twice() *Call
func (c *Call) Times(i int) *Call
func (c *Call) Maybe() *CallBuild structured test suites with setup/teardown hooks and lifecycle management.
// Suite is the base struct to embed in test suites
type Suite struct {
// contains filtered or unexported fields
}
// Access testing.T and assertion helpers
func (s *Suite) T() *testing.T
func (s *Suite) SetT(t *testing.T)
func (s *Suite) Assert() *assert.Assertions
func (s *Suite) Require() *require.Assertions
// Run the test suite
func Run(t *testing.T, suite TestingSuite)
// Lifecycle interfaces (implement in your suite)
type SetupAllSuite interface {
SetupSuite() // Runs once before all tests
}
type TearDownAllSuite interface {
TearDownSuite() // Runs once after all tests
}
type SetupTestSuite interface {
SetupTest() // Runs before each test
}
type TearDownTestSuite interface {
TearDownTest() // Runs after each test
}
type BeforeTest interface {
BeforeTest(suiteName, testName string)
}
type AfterTest interface {
AfterTest(suiteName, testName string)
}Deprecated: Use net/http/httptest from the standard library instead.
The http package provides deprecated HTTP testing utilities. It has been superseded by Go's standard library net/http/httptest package.
// TestResponseWriter - deprecated response writer mock
type TestResponseWriter struct {
StatusCode int
Output string
}
// TestRoundTripper - deprecated HTTP round tripper mock
type TestRoundTripper struct {
mock.Mock
}Recommendation: For new code, use net/http/httptest.ResponseRecorder and httptest.Server instead of this package.
Testify is organized into focused, composable packages:
The packages can be used independently or combined as needed.
Use assert when:
Use require when:
Instead of passing t to every assertion:
func TestExample(t *testing.T) {
a := assert.New(t)
a.Equal(expected, actual)
a.NoError(err)
a.True(condition)
}All assertion functions have an "f" variant for formatted messages:
assert.Equalf(t, expected, actual, "failed for user %s", username)
assert.NoErrorf(t, err, "error calling %s", endpoint)For flexible mock expectations:
import "github.com/stretchr/testify/mock"
// Match any value
m.On("Method", mock.Anything).Return(result)
// Match any value of specific type
m.On("Method", mock.AnythingOfType("string")).Return(result)
// Match specific type
m.On("Method", mock.IsType(MyType{})).Return(result)
// Custom matcher
m.On("Method", mock.MatchedBy(func(val int) bool {
return val > 10
})).Return(result)Implement these interfaces in your suite struct to add lifecycle hooks:
type MyTestSuite struct {
suite.Suite
db *Database
}
// Once before all tests
func (s *MyTestSuite) SetupSuite() {
s.db = OpenDatabase()
}
// Before each test
func (s *MyTestSuite) SetupTest() {
s.db.BeginTransaction()
}
// After each test
func (s *MyTestSuite) TearDownTest() {
s.db.Rollback()
}
// Once after all tests
func (s *MyTestSuite) TearDownSuite() {
s.db.Close()
}Testify assertions handle errors explicitly through assertion functions:
Error(t, err) - Asserts an error occurredNoError(t, err) - Asserts no error occurredEqualError(t, err, "message") - Asserts specific error messageErrorContains(t, err, "substring") - Asserts error message contains substringErrorIs(t, err, target) - Asserts error chain contains target (Go 1.13+)ErrorAs(t, err, &target) - Asserts error chain matches type (Go 1.13+)Mock objects can also be configured to return errors:
m.On("Get", "key").Return("", errors.New("not found"))