or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

assert.mdhttp.mdindex.mdmock.mdrequire.mdsuite.md
tile.json

index.mddocs/

Testify

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.

Package Information

  • Package Name: testify
  • Package Type: go
  • Language: Go
  • Installation: go get github.com/stretchr/testify@v1.11.1
  • Module: github.com/stretchr/testify
  • Version: v1.11.1

Core Imports

import (
    "github.com/stretchr/testify/assert"
    "github.com/stretchr/testify/require"
    "github.com/stretchr/testify/mock"
    "github.com/stretchr/testify/suite"
)

Basic Usage

Simple Assertions

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)
}

Strict Assertions with require

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)
}

Mocking

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)
}

Test Suites

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))
}

Capabilities

Assertion Functions (assert package)

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{}) bool

Assert Package - Complete API

Strict Assertion Functions (require package)

The 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{}) bool

Require Package - Complete API

Mock Objects (mock package)

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() *Call

Mock Package - Complete API

Test Suites (suite package)

Build 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)
}

Suite Package - Complete API

HTTP Testing Utilities (http package - Deprecated)

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
}

HTTP Package - Complete API

Recommendation: For new code, use net/http/httptest.ResponseRecorder and httptest.Server instead of this package.

Architecture

Testify is organized into focused, composable packages:

  1. assert: Foundation for all assertions, returns bool to allow test continuation
  2. require: Wrapper around assert that stops execution on failure
  3. mock: Independent mocking framework with expectation tracking
  4. suite: Test organization layer that integrates with assert/require
  5. http: Minimal HTTP testing utilities (deprecated features)

The packages can be used independently or combined as needed.

Common Patterns

Choosing assert vs require

Use assert when:

  • You want to collect multiple failures in one test
  • Subsequent assertions don't depend on previous ones
  • You're checking multiple independent conditions

Use require when:

  • A failure makes the rest of the test meaningless
  • Subsequent code would panic if the assertion fails
  • Setting up critical test preconditions

Assertion Wrapper Pattern

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)
}

Formatted Assertions

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)

Mock Argument Matchers

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)

Suite Lifecycle Hooks

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()
}

Error Handling

Testify assertions handle errors explicitly through assertion functions:

  • Error(t, err) - Asserts an error occurred
  • NoError(t, err) - Asserts no error occurred
  • EqualError(t, err, "message") - Asserts specific error message
  • ErrorContains(t, err, "substring") - Asserts error message contains substring
  • ErrorIs(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"))