or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

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

require.mddocs/

Require Package

The require package provides strict assertion functions that stop test execution immediately on first failure. It has an identical API to the assert package, but calls t.FailNow() on failure instead of t.Fail().

Package Information

  • Package Name: require
  • Package Type: go
  • Language: Go
  • Module: github.com/stretchr/testify/require

Import

import "github.com/stretchr/testify/require"

Overview

The require package is a wrapper around the assert package that stops test execution immediately when an assertion fails. This is useful for:

  • Setting up critical test preconditions
  • Validating assumptions that make subsequent code meaningless if false
  • Preventing panics from nil pointer dereferences
  • Failing fast when test setup fails

Basic Usage

import (
    "testing"
    "github.com/stretchr/testify/require"
)

func TestCriticalOperations(t *testing.T) {
    // If connection fails, stop immediately
    conn, err := database.Connect()
    require.NoError(t, err)
    require.NotNil(t, conn)

    // This code only runs if above assertions pass
    result, err := conn.Query("SELECT * FROM users")
    require.NoError(t, err)
    require.NotEmpty(t, result)

    // Using Require wrapper for cleaner syntax
    r := require.New(t)
    r.Equal(expected, actual)
    r.True(condition)
}

Key Difference from Assert

// Using assert - test continues after failure
assert.NotNil(t, obj)
result := obj.DoSomething() // May panic if obj is nil

// Using require - test stops immediately on failure
require.NotNil(t, obj)
result := obj.DoSomething() // Only runs if obj is not nil

Core Types

The require package provides the same types as assert:

// TestingT is the minimal interface required
type TestingT interface {
    Errorf(format string, args ...interface{})
    FailNow()
}

// Assertions wraps a TestingT for cleaner syntax
type Assertions struct {
    t TestingT
}

// CollectT collects errors without failing immediately
type CollectT struct {
    // contains filtered or unexported fields
}

// Function types
type Comparison func() (success bool)
type ComparisonAssertionFunc func(TestingT, interface{}, interface{}, ...interface{}) bool
type ValueAssertionFunc func(TestingT, interface{}, ...interface{}) bool
type BoolAssertionFunc func(TestingT, bool, ...interface{}) bool
type ErrorAssertionFunc func(TestingT, error, ...interface{}) bool
type PanicTestFunc func()
type PanicAssertionFunc func(TestingT, PanicTestFunc, ...interface{}) bool

Constructor

func New(t TestingT) *Assertions

Creates a new Assertions instance for cleaner syntax.

Complete API Reference

The require package provides identical functions to assert. All functions have the same signatures and behavior, except they call t.FailNow() on failure instead of t.Fail().

Equality Assertions

func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
func Equalf(t TestingT, expected, actual interface{}, msg string, args ...interface{}) bool
func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
func NotEqualf(t TestingT, expected, actual interface{}, msg string, args ...interface{}) bool
func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
func EqualValuesf(t TestingT, expected, actual interface{}, msg string, args ...interface{}) bool
func NotEqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
func NotEqualValuesf(t TestingT, expected, actual interface{}, msg string, args ...interface{}) bool
func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
func Exactlyf(t TestingT, expected, actual interface{}, msg string, args ...interface{}) bool
func EqualExportedValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
func EqualExportedValuesf(t TestingT, expected, actual interface{}, msg string, args ...interface{}) bool
func Same(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
func Samef(t TestingT, expected, actual interface{}, msg string, args ...interface{}) bool
func NotSame(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
func NotSamef(t TestingT, expected, actual interface{}, msg string, args ...interface{}) bool

Numeric Comparison Assertions

func Greater(t TestingT, e1, e2 interface{}, msgAndArgs ...interface{}) bool
func Greaterf(t TestingT, e1, e2 interface{}, msg string, args ...interface{}) bool
func GreaterOrEqual(t TestingT, e1, e2 interface{}, msgAndArgs ...interface{}) bool
func GreaterOrEqualf(t TestingT, e1, e2 interface{}, msg string, args ...interface{}) bool
func Less(t TestingT, e1, e2 interface{}, msgAndArgs ...interface{}) bool
func Lessf(t TestingT, e1, e2 interface{}, msg string, args ...interface{}) bool
func LessOrEqual(t TestingT, e1, e2 interface{}, msgAndArgs ...interface{}) bool
func LessOrEqualf(t TestingT, e1, e2 interface{}, msg string, args ...interface{}) bool
func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool
func InDeltaf(t TestingT, expected, actual interface{}, delta float64, msg string, args ...interface{}) bool
func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool
func InDeltaSlicef(t TestingT, expected, actual interface{}, delta float64, msg string, args ...interface{}) bool
func InDeltaMapValues(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool
func InDeltaMapValuesf(t TestingT, expected, actual interface{}, delta float64, msg string, args ...interface{}) bool
func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool
func InEpsilonf(t TestingT, expected, actual interface{}, epsilon float64, msg string, args ...interface{}) bool
func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool
func InEpsilonSlicef(t TestingT, expected, actual interface{}, epsilon float64, msg string, args ...interface{}) bool
func Positive(t TestingT, e interface{}, msgAndArgs ...interface{}) bool
func Positivef(t TestingT, e interface{}, msg string, args ...interface{}) bool
func Negative(t TestingT, e interface{}, msgAndArgs ...interface{}) bool
func Negativef(t TestingT, e interface{}, msg string, args ...interface{}) bool

Boolean Assertions

func True(t TestingT, value bool, msgAndArgs ...interface{}) bool
func Truef(t TestingT, value bool, msg string, args ...interface{}) bool
func False(t TestingT, value bool, msgAndArgs ...interface{}) bool
func Falsef(t TestingT, value bool, msg string, args ...interface{}) bool

Nil Assertions

func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool
func Nilf(t TestingT, object interface{}, msg string, args ...interface{}) bool
func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool
func NotNilf(t TestingT, object interface{}, msg string, args ...interface{}) bool

Empty/Zero Assertions

func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool
func Emptyf(t TestingT, object interface{}, msg string, args ...interface{}) bool
func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool
func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{}) bool
func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool
func Zerof(t TestingT, i interface{}, msg string, args ...interface{}) bool
func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool
func NotZerof(t TestingT, i interface{}, msg string, args ...interface{}) bool

Error Assertions

func Error(t TestingT, err error, msgAndArgs ...interface{}) bool
func Errorf(t TestingT, err error, msg string, args ...interface{}) bool
func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool
func NoErrorf(t TestingT, err error, msg string, args ...interface{}) bool
func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool
func EqualErrorf(t TestingT, theError error, errString string, msg string, args ...interface{}) bool
func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...interface{}) bool
func ErrorContainsf(t TestingT, theError error, contains string, msg string, args ...interface{}) bool
func ErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool
func ErrorIsf(t TestingT, err, target error, msg string, args ...interface{}) bool
func NotErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool
func NotErrorIsf(t TestingT, err, target error, msg string, args ...interface{}) bool
func ErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interface{}) bool
func ErrorAsf(t TestingT, err error, target interface{}, msg string, args ...interface{}) bool
func NotErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interface{}) bool
func NotErrorAsf(t TestingT, err error, target interface{}, msg string, args ...interface{}) bool

Collection Assertions

func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool
func Containsf(t TestingT, s, contains interface{}, msg string, args ...interface{}) bool
func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool
func NotContainsf(t TestingT, s, contains interface{}, msg string, args ...interface{}) bool
func ElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) bool
func ElementsMatchf(t TestingT, listA, listB interface{}, msg string, args ...interface{}) bool
func NotElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) bool
func NotElementsMatchf(t TestingT, listA, listB interface{}, msg string, args ...interface{}) bool
func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool
func Lenf(t TestingT, object interface{}, length int, msg string, args ...interface{}) bool
func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) bool
func Subsetf(t TestingT, list, subset interface{}, msg string, args ...interface{}) bool
func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) bool
func NotSubsetf(t TestingT, list, subset interface{}, msg string, args ...interface{}) bool

Ordering Assertions

func IsIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool
func IsIncreasingf(t TestingT, object interface{}, msg string, args ...interface{}) bool
func IsDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool
func IsDecreasingf(t TestingT, object interface{}, msg string, args ...interface{}) bool
func IsNonIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool
func IsNonIncreasingf(t TestingT, object interface{}, msg string, args ...interface{}) bool
func IsNonDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool
func IsNonDecreasingf(t TestingT, object interface{}, msg string, args ...interface{}) bool

Type Assertions

func IsType(t TestingT, expectedType, object interface{}, msgAndArgs ...interface{}) bool
func IsTypef(t TestingT, expectedType, object interface{}, msg string, args ...interface{}) bool
func IsNotType(t TestingT, theType, object interface{}, msgAndArgs ...interface{}) bool
func IsNotTypef(t TestingT, theType, object interface{}, msg string, args ...interface{}) bool
func Implements(t TestingT, interfaceObject, object interface{}, msgAndArgs ...interface{}) bool
func Implementsf(t TestingT, interfaceObject, object interface{}, msg string, args ...interface{}) bool
func NotImplements(t TestingT, interfaceObject, object interface{}, msgAndArgs ...interface{}) bool
func NotImplementsf(t TestingT, interfaceObject, object interface{}, msg string, args ...interface{}) bool

String/Regex Assertions

func Regexp(t TestingT, rx, str interface{}, msgAndArgs ...interface{}) bool
func Regexpf(t TestingT, rx, str interface{}, msg string, args ...interface{}) bool
func NotRegexp(t TestingT, rx, str interface{}, msgAndArgs ...interface{}) bool
func NotRegexpf(t TestingT, rx, str interface{}, msg string, args ...interface{}) bool

Panic Assertions

func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool
func Panicsf(t TestingT, f PanicTestFunc, msg string, args ...interface{}) bool
func PanicsWithValue(t TestingT, expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool
func PanicsWithValuef(t TestingT, expected interface{}, f PanicTestFunc, msg string, args ...interface{}) bool
func PanicsWithError(t TestingT, errString string, f PanicTestFunc, msgAndArgs ...interface{}) bool
func PanicsWithErrorf(t TestingT, errString string, f PanicTestFunc, msg string, args ...interface{}) bool
func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool
func NotPanicsf(t TestingT, f PanicTestFunc, msg string, args ...interface{}) bool

File/Directory Assertions

func FileExists(t TestingT, path string, msgAndArgs ...interface{}) bool
func FileExistsf(t TestingT, path string, msg string, args ...interface{}) bool
func NoFileExists(t TestingT, path string, msgAndArgs ...interface{}) bool
func NoFileExistsf(t TestingT, path string, msg string, args ...interface{}) bool
func DirExists(t TestingT, path string, msgAndArgs ...interface{}) bool
func DirExistsf(t TestingT, path string, msg string, args ...interface{}) bool
func NoDirExists(t TestingT, path string, msgAndArgs ...interface{}) bool
func NoDirExistsf(t TestingT, path string, msg string, args ...interface{}) bool

JSON/YAML Assertions

func JSONEq(t TestingT, expected, actual string, msgAndArgs ...interface{}) bool
func JSONEqf(t TestingT, expected, actual string, msg string, args ...interface{}) bool
func YAMLEq(t TestingT, expected, actual string, msgAndArgs ...interface{}) bool
func YAMLEqf(t TestingT, expected, actual string, msg string, args ...interface{}) bool

Conditional/Temporal Assertions

func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool
func Conditionf(t TestingT, comp Comparison, msg string, args ...interface{}) bool
func Eventually(t TestingT, condition func() bool, waitFor, tick time.Duration, msgAndArgs ...interface{}) bool
func Eventuallyf(t TestingT, condition func() bool, waitFor, tick time.Duration, msg string, args ...interface{}) bool
func EventuallyWithT(t TestingT, condition func(collect *CollectT), waitFor, tick time.Duration, msgAndArgs ...interface{}) bool
func EventuallyWithTf(t TestingT, condition func(collect *CollectT), waitFor, tick time.Duration, msg string, args ...interface{}) bool
func Never(t TestingT, condition func() bool, waitFor, tick time.Duration, msgAndArgs ...interface{}) bool
func Neverf(t TestingT, condition func() bool, waitFor, tick time.Duration, msg string, args ...interface{}) bool
func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool
func WithinDurationf(t TestingT, expected, actual time.Time, delta time.Duration, msg string, args ...interface{}) bool
func WithinRange(t TestingT, actual, start, end time.Time, msgAndArgs ...interface{}) bool
func WithinRangef(t TestingT, actual, start, end time.Time, msg string, args ...interface{}) bool
func NotWithinRange(t TestingT, actual, start, end time.Time, msgAndArgs ...interface{}) bool
func NotWithinRangef(t TestingT, actual, start, end time.Time, msg string, args ...interface{}) bool

HTTP Assertions

func HTTPSuccess(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool
func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msg string, args ...interface{}) bool
func HTTPRedirect(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool
func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msg string, args ...interface{}) bool
func HTTPError(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool
func HTTPErrorf(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msg string, args ...interface{}) bool
func HTTPStatusCode(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, statuscode int, msgAndArgs ...interface{}) bool
func HTTPStatusCodef(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, statuscode int, msg string, args ...interface{}) bool
func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool
func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool
func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool
func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool

Utility Functions

func CallerInfo() []string
func HTTPBody(handler http.HandlerFunc, method, url string, values url.Values) string
func ObjectsAreEqual(expected, actual interface{}) bool
func ObjectsAreEqualValues(expected, actual interface{}) bool
func ObjectsExportedFieldsAreEqual(expected, actual interface{}) bool

Failure Functions

func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool
func Failf(t TestingT, failureMessage string, msg string, args ...interface{}) bool
func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool
func FailNowf(t TestingT, failureMessage string, msg string, args ...interface{}) bool

Usage Examples

Critical Preconditions

func TestDatabaseOperations(t *testing.T) {
    // Require connection to proceed
    db, err := sql.Open("postgres", dsn)
    require.NoError(t, err, "failed to open database")
    require.NotNil(t, db, "database connection is nil")
    defer db.Close()

    // Only runs if connection succeeded
    err = db.Ping()
    require.NoError(t, err, "failed to ping database")

    // Safe to use db from this point
    rows, err := db.Query("SELECT * FROM users")
    require.NoError(t, err)
    defer rows.Close()
}

Preventing Panics

func TestUserLookup(t *testing.T) {
    users := []User{{ID: 1, Name: "Alice"}, {ID: 2, Name: "Bob"}}

    // Require valid index to prevent panic
    require.Greater(t, len(users), 0, "users slice must not be empty")

    // Safe to access first element
    firstUser := users[0]
    require.Equal(t, "Alice", firstUser.Name)
}

Test Setup Validation

func TestWithComplexSetup(t *testing.T) {
    // Setup must succeed for test to be meaningful
    config := LoadConfig("test-config.yaml")
    require.NotNil(t, config, "failed to load config")
    require.NotEmpty(t, config.APIKey, "API key must be set")

    server := NewServer(config)
    require.NotNil(t, server, "failed to create server")

    err := server.Start()
    require.NoError(t, err, "server failed to start")
    defer server.Stop()

    // Test runs only if all setup succeeded
    response := server.HandleRequest(testRequest)
    require.Equal(t, 200, response.StatusCode)
}

See Also

  • Assert Package - Complete documentation of all assertion functions (same API, different failure behavior)
  • Suite Package - Test suite framework that integrates with require