or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

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

assert.mddocs/

Testify Assert Package

The assert package provides comprehensive testing tools for use with the normal Go testing system. All assertion functions return a bool value indicating whether the assertion has passed, allowing test execution to continue after failures.

Package Information

  • Package Name: github.com/stretchr/testify/assert
  • Package Type: Go module
  • Language: Go
  • Installation: go get github.com/stretchr/testify/assert

Import Statement

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

Basic Usage

The assert package can be used in two ways:

Direct Function Calls

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

func TestSomething(t *testing.T) {
    var a string = "Hello"
    var b string = "Hello"

    assert.Equal(t, a, b, "The two words should be the same.")
}

Using Assertions Struct

For tests with many assertions, create an Assertions instance:

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

func TestSomething(t *testing.T) {
    assert := assert.New(t)

    var a string = "Hello"
    var b string = "Hello"

    assert.Equal(a, b, "The two words should be the same.")
}

Core Types

TestingT Interface

The minimal interface required for assertions, satisfied by *testing.T and *testing.B.

type TestingT interface {
    Errorf(format string, args ...interface{})
}

Assertions Struct

A wrapper type that allows chaining assertions without passing *testing.T to each call.

type Assertions struct {
    // Has unexported fields
}

Constructor:

func New(t TestingT) *Assertions

Creates a new Assertions object for the specified TestingT. All assertion functions available as package-level functions are also available as methods on this type.

CollectT Struct

Collects errors without failing immediately, used with Eventually/EventuallyWithT.

type CollectT struct {
    // Has unexported fields
}

Methods:

func (c *CollectT) Errorf(format string, args ...interface{})
func (c *CollectT) FailNow()
func (CollectT) Helper()
func (*CollectT) Copy(TestingT)
func (*CollectT) Reset()
  • Errorf - Collects the error without failing the test
  • FailNow - Stops execution by calling runtime.Goexit
  • Helper - Like testing.T.Helper but does nothing
  • Copy - Deprecated: Panics when called. Was for internal use.
  • Reset - Deprecated: Panics when called. Was for internal use.

Function Types

// CompareType is an alias for internal comparison results
type CompareType = compareResult

CompareType is exported for compatibility but is primarily used internally for comparison operations.

// Comparison is a custom function that returns true on success and false on failure
type Comparison func() (success bool)

// ComparisonAssertionFunc is for comparing two values
type ComparisonAssertionFunc func(TestingT, interface{}, interface{}, ...interface{}) bool

// ValueAssertionFunc is for validating a single value
type ValueAssertionFunc func(TestingT, interface{}, ...interface{}) bool

// BoolAssertionFunc is for validating a bool value
type BoolAssertionFunc func(TestingT, bool, ...interface{}) bool

// ErrorAssertionFunc is for validating an error value
type ErrorAssertionFunc func(TestingT, error, ...interface{}) bool

// PanicTestFunc represents a func that takes no arguments and returns nothing
type PanicTestFunc func()

// PanicAssertionFunc is for validating a panic value
type PanicAssertionFunc func(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool

Variables

var AnError = errors.New("assert.AnError general error for testing")

AnError is an error instance useful for testing. If the code does not care about error specifics and only needs to return the error for example, this error should be used to make the test code more readable.

Equality Assertions

Equal

Asserts that two objects are equal. Pointer variable equality is determined based on the equality of the referenced values (as opposed to memory addresses). Function equality cannot be determined and will always fail.

func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
func Equalf(t TestingT, expected, actual interface{}, msg string, args ...interface{}) bool

Example:

assert.Equal(t, 123, 123)

EqualValues

Asserts that two objects are equal or convertible to the larger type and equal.

func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
func EqualValuesf(t TestingT, expected, actual interface{}, msg string, args ...interface{}) bool

Example:

assert.EqualValues(t, uint32(123), int32(123))

Exactly

Asserts that two objects are equal in value and type.

func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
func Exactlyf(t TestingT, expected, actual interface{}, msg string, args ...interface{}) bool

Example:

assert.Exactly(t, int32(123), int32(123))

EqualExportedValues

Asserts that the types of two objects are equal and their public fields are also equal. This is useful for comparing structs that have private fields that could potentially differ.

func EqualExportedValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
func EqualExportedValuesf(t TestingT, expected, actual interface{}, msg string, args ...interface{}) bool

Example:

type S struct {
    Exported    int
    notExported int
}
assert.EqualExportedValues(t, S{1, 2}, S{1, 3}) // passes
assert.EqualExportedValues(t, S{1, 2}, S{2, 3}) // fails

NotEqual

Asserts that the specified values are NOT equal.

func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
func NotEqualf(t TestingT, expected, actual interface{}, msg string, args ...interface{}) bool

NotEqualValues

Asserts that two objects are not equal even when converted to the same type.

func NotEqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
func NotEqualValuesf(t TestingT, expected, actual interface{}, msg string, args ...interface{}) bool

Same

Asserts that two pointers reference the same object. Both arguments must be pointer variables. Pointer variable sameness is determined based on the equality of both type and value.

func Same(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool
func Samef(t TestingT, expected, actual interface{}, msg string, args ...interface{}) bool

Example:

assert.Same(t, ptr1, ptr2)

NotSame

Asserts that two pointers do not reference the same object.

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

Greater

Asserts that the first element is greater than the second.

func Greater(t TestingT, e1, e2 interface{}, msgAndArgs ...interface{}) bool
func Greaterf(t TestingT, e1, e2 interface{}, msg string, args ...interface{}) bool

Example:

assert.Greater(t, 2, 1)
assert.Greater(t, float64(2), float64(1))
assert.Greater(t, "b", "a")

GreaterOrEqual

Asserts that the first element is greater than or equal to the second.

func GreaterOrEqual(t TestingT, e1, e2 interface{}, msgAndArgs ...interface{}) bool
func GreaterOrEqualf(t TestingT, e1, e2 interface{}, msg string, args ...interface{}) bool

Less

Asserts that the first element is less than the second.

func Less(t TestingT, e1, e2 interface{}, msgAndArgs ...interface{}) bool
func Lessf(t TestingT, e1, e2 interface{}, msg string, args ...interface{}) bool

Example:

assert.Less(t, 1, 2)
assert.Less(t, float64(1), float64(2))
assert.Less(t, "a", "b")

LessOrEqual

Asserts that the first element is less than or equal to the second.

func LessOrEqual(t TestingT, e1, e2 interface{}, msgAndArgs ...interface{}) bool
func LessOrEqualf(t TestingT, e1, e2 interface{}, msg string, args ...interface{}) bool

InDelta

Asserts that the two numerals are within delta of each other.

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

Example:

assert.InDelta(t, math.Pi, 22/7.0, 0.01)

InDeltaSlice

The same as InDelta, except it compares two slices.

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

InDeltaMapValues

The same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys.

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

InEpsilon

Asserts that expected and actual have a relative error less than epsilon.

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

InEpsilonSlice

The same as InEpsilon, except it compares each value from two slices.

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

Positive

Asserts that the specified element is positive.

func Positive(t TestingT, e interface{}, msgAndArgs ...interface{}) bool
func Positivef(t TestingT, e interface{}, msg string, args ...interface{}) bool

Example:

assert.Positive(t, 1)
assert.Positive(t, 1.23)

Negative

Asserts that the specified element is negative.

func Negative(t TestingT, e interface{}, msgAndArgs ...interface{}) bool
func Negativef(t TestingT, e interface{}, msg string, args ...interface{}) bool

Example:

assert.Negative(t, -1)
assert.Negative(t, -1.23)

Boolean Assertions

True

Asserts that the specified value is true.

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

Example:

assert.True(t, myBool)

False

Asserts that the specified value is false.

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

Example:

assert.False(t, myBool)

Nil Assertions

Nil

Asserts that the specified object is nil.

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

Example:

assert.Nil(t, err)

NotNil

Asserts that the specified object is not nil.

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

Example:

assert.NotNil(t, err)

Empty/Zero Assertions

Empty

Asserts that the given value is "empty". Zero values are "empty". Arrays are "empty" if every element is the zero value of the type. Slices, maps and channels with zero length are "empty". Pointer values are "empty" if the pointer is nil or if the pointed value is "empty".

func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool
func Emptyf(t TestingT, object interface{}, msg string, args ...interface{}) bool

Example:

assert.Empty(t, obj)

NotEmpty

Asserts that the specified object is NOT Empty.

func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool
func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{}) bool

Example:

if assert.NotEmpty(t, obj) {
    assert.Equal(t, "two", obj[1])
}

Zero

Asserts that i is the zero value for its type.

func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool
func Zerof(t TestingT, i interface{}, msg string, args ...interface{}) bool

NotZero

Asserts that i is not the zero value for its type.

func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool
func NotZerof(t TestingT, i interface{}, msg string, args ...interface{}) bool

Error Assertions

Error

Asserts that a function returned an error (i.e. not nil).

func Error(t TestingT, err error, msgAndArgs ...interface{}) bool
func Errorf(t TestingT, err error, msg string, args ...interface{}) bool

Example:

actualObj, err := SomeFunction()
assert.Error(t, err)

NoError

Asserts that a function returned no error (i.e. nil).

func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool
func NoErrorf(t TestingT, err error, msg string, args ...interface{}) bool

Example:

actualObj, err := SomeFunction()
if assert.NoError(t, err) {
    assert.Equal(t, expectedObj, actualObj)
}

EqualError

Asserts that a function returned an error (i.e. not nil) and that it is equal to the provided error.

func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool
func EqualErrorf(t TestingT, theError error, errString string, msg string, args ...interface{}) bool

Example:

actualObj, err := SomeFunction()
assert.EqualError(t, err, expectedErrorString)

ErrorContains

Asserts that a function returned an error (i.e. not nil) and that the error contains the specified substring.

func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...interface{}) bool
func ErrorContainsf(t TestingT, theError error, contains string, msg string, args ...interface{}) bool

Example:

actualObj, err := SomeFunction()
assert.ErrorContains(t, err, expectedErrorSubString)

ErrorIs

Asserts that at least one of the errors in err's chain matches target. This is a wrapper for errors.Is.

func ErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool
func ErrorIsf(t TestingT, err, target error, msg string, args ...interface{}) bool

NotErrorIs

Asserts that none of the errors in err's chain matches target. This is a wrapper for errors.Is.

func NotErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool
func NotErrorIsf(t TestingT, err, target error, msg string, args ...interface{}) bool

ErrorAs

Asserts that at least one of the errors in err's chain matches target, and if so, sets target to that error value. This is a wrapper for errors.As.

func ErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interface{}) bool
func ErrorAsf(t TestingT, err error, target interface{}, msg string, args ...interface{}) bool

NotErrorAs

Asserts that none of the errors in err's chain matches target, but if so, sets target to that error value.

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

Contains

Asserts that the specified string, list (array, slice...) or map contains the specified substring or element.

func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool
func Containsf(t TestingT, s, contains interface{}, msg string, args ...interface{}) bool

Example:

assert.Contains(t, "Hello World", "World")
assert.Contains(t, []string{"Hello", "World"}, "World")
assert.Contains(t, map[string]string{"Hello": "World"}, "Hello")

NotContains

Asserts that the specified string, list (array, slice...) or map does NOT contain the specified substring or element.

func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool
func NotContainsf(t TestingT, s, contains interface{}, msg string, args ...interface{}) bool

Example:

assert.NotContains(t, "Hello World", "Earth")
assert.NotContains(t, []string{"Hello", "World"}, "Earth")
assert.NotContains(t, map[string]string{"Hello": "World"}, "Earth")

ElementsMatch

Asserts that the specified listA (array, slice...) is equal to specified listB (array, slice...) ignoring the order of the elements. If there are duplicate elements, the number of appearances of each of them in both lists should match.

func ElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) bool
func ElementsMatchf(t TestingT, listA, listB interface{}, msg string, args ...interface{}) bool

Example:

assert.ElementsMatch(t, []int{1, 3, 2, 3}, []int{1, 3, 3, 2})

NotElementsMatch

Asserts that the specified listA (array, slice...) is NOT equal to specified listB (array, slice...) ignoring the order of the elements. This is an inverse of ElementsMatch.

func NotElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) bool
func NotElementsMatchf(t TestingT, listA, listB interface{}, msg string, args ...interface{}) bool

Example:

assert.NotElementsMatch(t, []int{1, 1, 2, 3}, []int{1, 1, 2, 3}) // fails
assert.NotElementsMatch(t, []int{1, 1, 2, 3}, []int{1, 2, 3})    // passes
assert.NotElementsMatch(t, []int{1, 2, 3}, []int{1, 2, 4})       // passes

Len

Asserts that the specified object has specific length. Len also fails if the object has a type that len() does not accept.

func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool
func Lenf(t TestingT, object interface{}, length int, msg string, args ...interface{}) bool

Example:

assert.Len(t, mySlice, 3)

Subset

Asserts that the list (array, slice, or map) contains all elements given in the subset (array, slice, or map). Map elements are key-value pairs unless compared with an array or slice where only the map key is evaluated.

func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) bool
func Subsetf(t TestingT, list, subset interface{}, msg string, args ...interface{}) bool

Example:

assert.Subset(t, []int{1, 2, 3}, []int{1, 2})
assert.Subset(t, map[string]int{"x": 1, "y": 2}, map[string]int{"x": 1})
assert.Subset(t, []int{1, 2, 3}, map[int]string{1: "one", 2: "two"})
assert.Subset(t, map[string]int{"x": 1, "y": 2}, []string{"x"})

NotSubset

Asserts that the list (array, slice, or map) does NOT contain all elements given in the subset (array, slice, or map).

func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) bool
func NotSubsetf(t TestingT, list, subset interface{}, msg string, args ...interface{}) bool

Example:

assert.NotSubset(t, []int{1, 3, 4}, []int{1, 2})
assert.NotSubset(t, map[string]int{"x": 1, "y": 2}, map[string]int{"z": 3})

Ordering Assertions

IsIncreasing

Asserts that the collection is strictly increasing.

func IsIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool
func IsIncreasingf(t TestingT, object interface{}, msg string, args ...interface{}) bool

Example:

assert.IsIncreasing(t, []int{1, 2, 3})
assert.IsIncreasing(t, []float64{1, 2})
assert.IsIncreasing(t, []string{"a", "b"})

IsDecreasing

Asserts that the collection is strictly decreasing.

func IsDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool
func IsDecreasingf(t TestingT, object interface{}, msg string, args ...interface{}) bool

Example:

assert.IsDecreasing(t, []int{2, 1, 0})
assert.IsDecreasing(t, []float64{2, 1})
assert.IsDecreasing(t, []string{"b", "a"})

IsNonDecreasing

Asserts that the collection is non-decreasing (allows equal consecutive elements).

func IsNonDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool
func IsNonDecreasingf(t TestingT, object interface{}, msg string, args ...interface{}) bool

Example:

assert.IsNonDecreasing(t, []int{1, 1, 2})
assert.IsNonDecreasing(t, []float64{1, 2})
assert.IsNonDecreasing(t, []string{"a", "b"})

IsNonIncreasing

Asserts that the collection is non-increasing (allows equal consecutive elements).

func IsNonIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool
func IsNonIncreasingf(t TestingT, object interface{}, msg string, args ...interface{}) bool

Example:

assert.IsNonIncreasing(t, []int{2, 1, 1})
assert.IsNonIncreasing(t, []float64{2, 1})
assert.IsNonIncreasing(t, []string{"b", "a"})

Type Assertions

IsType

Asserts that the specified objects are of the same type.

func IsType(t TestingT, expectedType, object interface{}, msgAndArgs ...interface{}) bool
func IsTypef(t TestingT, expectedType, object interface{}, msg string, args ...interface{}) bool

Example:

assert.IsType(t, &MyStruct{}, &MyStruct{})

IsNotType

Asserts that the specified objects are not of the same type.

func IsNotType(t TestingT, theType, object interface{}, msgAndArgs ...interface{}) bool
func IsNotTypef(t TestingT, theType, object interface{}, msg string, args ...interface{}) bool

Example:

assert.IsNotType(t, &NotMyStruct{}, &MyStruct{})

Implements

Asserts that an object is implemented by the specified interface.

func Implements(t TestingT, interfaceObject, object interface{}, msgAndArgs ...interface{}) bool
func Implementsf(t TestingT, interfaceObject, object interface{}, msg string, args ...interface{}) bool

Example:

assert.Implements(t, (*MyInterface)(nil), new(MyObject))

NotImplements

Asserts that an object does not implement the specified interface.

func NotImplements(t TestingT, interfaceObject, object interface{}, msgAndArgs ...interface{}) bool
func NotImplementsf(t TestingT, interfaceObject, object interface{}, msg string, args ...interface{}) bool

Example:

assert.NotImplements(t, (*MyInterface)(nil), new(MyObject))

String/Regex Assertions

Regexp

Asserts that a specified regexp matches a string.

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

Example:

assert.Regexp(t, regexp.MustCompile("start"), "it's starting")
assert.Regexp(t, "start...$", "it's not starting")

NotRegexp

Asserts that a specified regexp does not match a string.

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

Example:

assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting")
assert.NotRegexp(t, "^start", "it's not starting")

Panic Assertions

Panics

Asserts that the code inside the specified PanicTestFunc panics.

func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool
func Panicsf(t TestingT, f PanicTestFunc, msg string, args ...interface{}) bool

Example:

assert.Panics(t, func(){ GoCrazy() })

PanicsWithValue

Asserts that the code inside the specified PanicTestFunc panics, and that the recovered panic value equals the expected panic value.

func PanicsWithValue(t TestingT, expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool
func PanicsWithValuef(t TestingT, expected interface{}, f PanicTestFunc, msg string, args ...interface{}) bool

Example:

assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() })

PanicsWithError

Asserts that the code inside the specified PanicTestFunc panics, and that the recovered panic value is an error that satisfies the EqualError comparison.

func PanicsWithError(t TestingT, errString string, f PanicTestFunc, msgAndArgs ...interface{}) bool
func PanicsWithErrorf(t TestingT, errString string, f PanicTestFunc, msg string, args ...interface{}) bool

Example:

assert.PanicsWithError(t, "crazy error", func(){ GoCrazy() })

NotPanics

Asserts that the code inside the specified PanicTestFunc does NOT panic.

func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool
func NotPanicsf(t TestingT, f PanicTestFunc, msg string, args ...interface{}) bool

Example:

assert.NotPanics(t, func(){ RemainCalm() })

File/Directory Assertions

FileExists

Checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file.

func FileExists(t TestingT, path string, msgAndArgs ...interface{}) bool
func FileExistsf(t TestingT, path string, msg string, args ...interface{}) bool

NoFileExists

Checks whether a file does not exist in a given path. It fails if the path points to an existing file only.

func NoFileExists(t TestingT, path string, msgAndArgs ...interface{}) bool
func NoFileExistsf(t TestingT, path string, msg string, args ...interface{}) bool

DirExists

Checks whether a directory exists in the given path. It also fails if the path is a file rather than a directory or there is an error checking whether it exists.

func DirExists(t TestingT, path string, msgAndArgs ...interface{}) bool
func DirExistsf(t TestingT, path string, msg string, args ...interface{}) bool

NoDirExists

Checks whether a directory does not exist in the given path. It fails if the path points to an existing directory only.

func NoDirExists(t TestingT, path string, msgAndArgs ...interface{}) bool
func NoDirExistsf(t TestingT, path string, msg string, args ...interface{}) bool

JSON/YAML Assertions

JSONEq

Asserts that two JSON strings are equivalent.

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

Example:

assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)

YAMLEq

Asserts that two YAML strings are equivalent.

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

YAML Sub-package

The assert/yaml sub-package provides YAML deserialization support for the assert package. It's primarily used internally by YAMLEq and YAMLEqf.

Import:

import "github.com/stretchr/testify/assert/yaml"

Function:

func Unmarshal(in []byte, out interface{}) error

Unmarshal is a wrapper around gopkg.in/yaml.v3.Unmarshal used for YAML deserialization.

Build Tags:

The yaml package supports alternative implementations via build tags:

  • testify_yaml_fail - Unmarshal always fails with an error
  • testify_yaml_custom - Unmarshal is a variable that must be initialized by the caller

This allows flexibility in YAML handling for different build scenarios or license compatibility requirements.

Conditional/Temporal Assertions

Condition

Uses a Comparison to assert a complex condition.

func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool
func Conditionf(t TestingT, comp Comparison, msg string, args ...interface{}) bool

Eventually

Asserts that given condition will be met in waitFor time, periodically checking target function each tick.

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

Example:

assert.Eventually(t, func() bool { return true; }, time.Second, 10*time.Millisecond)

EventuallyWithT

Asserts that given condition will be met in waitFor time, periodically checking target function each tick. In contrast to Eventually, it supplies a CollectT to the condition function, so that the condition function can use the CollectT to call other assertions. The condition is considered "met" if no errors are raised in a tick.

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

Example:

externalValue := false
go func() {
    time.Sleep(8*time.Second)
    externalValue = true
}()
assert.EventuallyWithT(t, func(c *assert.CollectT) {
    assert.True(c, externalValue, "expected 'externalValue' to be true")
}, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false")

Never

Asserts that the given condition doesn't satisfy in waitFor time, periodically checking the target function each tick.

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

Example:

assert.Never(t, func() bool { return false; }, time.Second, 10*time.Millisecond)

WithinDuration

Asserts that the two times are within duration delta of each other.

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

Example:

assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second)

WithinRange

Asserts that a time is within a time range (inclusive).

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

Example:

assert.WithinRange(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second))

NotWithinRange

Asserts that a time is not within a time range (inclusive).

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

HTTPSuccess

Asserts that a specified handler returns a success status code.

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

Example:

assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil)

HTTPRedirect

Asserts that a specified handler returns a redirect status code.

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

Example:

assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}})

HTTPError

Asserts that a specified handler returns an error status code.

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

Example:

assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}})

HTTPStatusCode

Asserts that a specified handler returns a specified status code.

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

Example:

assert.HTTPStatusCode(t, myHandler, "GET", "/notImplemented", nil, 501)

HTTPBodyContains

Asserts that a specified handler returns a body that contains a string.

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

Example:

assert.HTTPBodyContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky")

HTTPBodyNotContains

Asserts that a specified handler returns a body that does not contain a string.

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

Example:

assert.HTTPBodyNotContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky")

Utility Functions

CallerInfo

Returns an array of strings containing the file and line number of each stack frame leading from the current test to the assert call that failed.

func CallerInfo() []string

HTTPBody

Helper that returns HTTP body of the response. It returns empty string if building a new request fails.

func HTTPBody(handler http.HandlerFunc, method, url string, values url.Values) string

ObjectsAreEqual

Determines if two objects are considered equal. This function does no assertion of any kind.

func ObjectsAreEqual(expected, actual interface{}) bool

ObjectsAreEqualValues

Gets whether two objects are equal, or if their values are equal.

func ObjectsAreEqualValues(expected, actual interface{}) bool

ObjectsExportedFieldsAreEqual

Determines if the exported (public) fields of two objects are considered equal. This comparison of only exported fields is applied recursively to nested data structures. This function does no assertion of any kind.

func ObjectsExportedFieldsAreEqual(expected, actual interface{}) bool

Deprecated: Use EqualExportedValues instead.

Failure Functions

Fail

Reports a failure through the TestingT interface.

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

FailNow

Fails test immediately.

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