assert

package
v1.12.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 17, 2026 License: MIT Imports: 21 Imported by: 16,016

Documentation

Overview

Package assert provides a set of comprehensive testing tools for use with the normal Go testing system.

Note

All functions in this package return a bool value indicating whether the assertion has passed.

Example Usage

The following is a complete example using assert in a standard test function:

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.")

}

if you assert many times, use the format below:

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

Assertions

Assertions allow you to easily write test code, and are global funcs in the assert package. All assertion functions take, as the first argument, the *testing.T object provided by the testing framework. This allows the assertion funcs to write the failings and other details to the correct place.

Every assertion function also takes an optional string message as the final argument, allowing custom error messages to be appended to the message the assertion method outputs.

Index

Examples

Constants

This section is empty.

Variables

View Source
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.

Functions

func CallerInfo

func CallerInfo() []string

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 Condition

func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool

Condition uses a Comparison to assert a complex condition.

func Conditionf added in v1.2.0

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

Conditionf uses a Comparison to assert a complex condition.

func Contains

func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool

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

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

func Containsf added in v1.2.0

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

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

assert.Containsf(t, "Hello World", "World", "error message %s", "formatted")
assert.Containsf(t, ["Hello", "World"], "World", "error message %s", "formatted")
assert.Containsf(t, {"Hello": "World"}, "Hello", "error message %s", "formatted")

func DirExists added in v1.2.0

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

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

func DirExistsf added in v1.2.0

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

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

func ElementsMatch added in v1.2.0

func ElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) (ok bool)

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.

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

func ElementsMatchf added in v1.2.0

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

ElementsMatchf 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.

assert.ElementsMatchf(t, [1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted")

func Empty

func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool

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 (stricter than "empty").

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".

assert.Empty(t, obj)

func Emptyf added in v1.2.0

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

Emptyf asserts that the given value is "empty".

Zero values are "empty".

Arrays are "empty" if every element is the zero value of the type (stricter than "empty").

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".

assert.Emptyf(t, obj, "error message %s", "formatted")

func Equal

func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool

Equal asserts that two objects are equal.

assert.Equal(t, 123, 123)

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

func EqualError

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

EqualError asserts that a function returned a non-nil error (i.e. an error) and that it is equal to the provided error.

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

func EqualErrorf added in v1.2.0

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

EqualErrorf asserts that a function returned a non-nil error (i.e. an error) and that it is equal to the provided error.

actualObj, err := SomeFunction()
assert.EqualErrorf(t, err,  expectedErrorString, "error message %s", "formatted")

func EqualExportedValues added in v1.8.3

func EqualExportedValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool

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.

 type S struct {
	Exported     	int
	notExported   	int
 }
 assert.EqualExportedValues(t, S{1, 2}, S{1, 3}) => true
 assert.EqualExportedValues(t, S{1, 2}, S{2, 3}) => false

func EqualExportedValuesf added in v1.8.3

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

EqualExportedValuesf 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.

 type S struct {
	Exported     	int
	notExported   	int
 }
 assert.EqualExportedValuesf(t, S{1, 2}, S{1, 3}, "error message %s", "formatted") => true
 assert.EqualExportedValuesf(t, S{1, 2}, S{2, 3}, "error message %s", "formatted") => false

func EqualValues

func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool

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

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

func EqualValuesf added in v1.2.0

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

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

assert.EqualValuesf(t, uint32(123), int32(123), "error message %s", "formatted")

func Equalf added in v1.2.0

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

Equalf asserts that two objects are equal.

assert.Equalf(t, 123, 123, "error message %s", "formatted")

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

func Error

func Error(t TestingT, err error, msgAndArgs ...interface{}) bool

Error asserts that a function returned a non-nil error (ie. an error).

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

func ErrorAs added in v1.7.0

func ErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...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 ErrorAsf added in v1.7.0

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

ErrorAsf 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 ErrorContains added in v1.7.1

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

ErrorContains asserts that a function returned a non-nil error (i.e. an error) and that the error contains the specified substring.

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

func ErrorContainsf added in v1.7.1

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

ErrorContainsf asserts that a function returned a non-nil error (i.e. an error) and that the error contains the specified substring.

actualObj, err := SomeFunction()
assert.ErrorContainsf(t, err,  expectedErrorSubString, "error message %s", "formatted")

func ErrorIs added in v1.7.0

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

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

func ErrorIsf added in v1.7.0

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

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

func Errorf added in v1.2.0

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

Errorf asserts that a function returned a non-nil error (ie. an error).

actualObj, err := SomeFunction()
assert.Errorf(t, err, "error message %s", "formatted")

func Eventually added in v1.4.0

func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool

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

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

func EventuallyWithT added in v1.8.3

func EventuallyWithT(t TestingT, condition func(collect *CollectT), waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool

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. The supplied CollectT collects all errors from one tick (if there are any). If the condition is not met before waitFor, the collected errors of the last tick are copied to t.

externalValue := false
go func() {
	time.Sleep(8*time.Second)
	externalValue = true
}()
assert.EventuallyWithT(t, func(c *assert.CollectT) {
	// add assertions as needed; any assertion failure will fail the current tick
	assert.True(c, externalValue, "expected 'externalValue' to be true")
}, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false")

func EventuallyWithTf added in v1.8.3

func EventuallyWithTf(t TestingT, condition func(collect *CollectT), waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool

EventuallyWithTf 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. The supplied CollectT collects all errors from one tick (if there are any). If the condition is not met before waitFor, the collected errors of the last tick are copied to t.

externalValue := false
go func() {
	time.Sleep(8*time.Second)
	externalValue = true
}()
assert.EventuallyWithTf(t, func(c *assert.CollectT) {
	// add assertions as needed; any assertion failure will fail the current tick
	assert.True(c, externalValue, "expected 'externalValue' to be true")
}, 10*time.Second, 1*time.Second, "error message %s", "formatted")

func Eventuallyf added in v1.4.0

func Eventuallyf(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool

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

assert.Eventuallyf(t, func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted")

func Exactly

func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool

Exactly asserts that two objects are equal in value and type.

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

func Exactlyf added in v1.2.0

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

Exactlyf asserts that two objects are equal in value and type.

assert.Exactlyf(t, int32(123), int64(123), "error message %s", "formatted")

func Fail

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

Fail reports a failure through

func FailNow

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

FailNow fails test

func FailNowf added in v1.2.0

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

FailNowf fails test

func Failf added in v1.2.0

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

Failf reports a failure through

func False

func False(t TestingT, value bool, msgAndArgs ...interface{}) bool

False asserts that the specified value is false.

assert.False(t, myBool)

func Falsef added in v1.2.0

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

Falsef asserts that the specified value is false.

assert.Falsef(t, myBool, "error message %s", "formatted")

func FileExists added in v1.2.0

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

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 FileExistsf added in v1.2.0

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

FileExistsf 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 Greater added in v1.4.0

func Greater(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool

Greater asserts that the first element is greater than the second

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

func GreaterOrEqual added in v1.4.0

func GreaterOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool

GreaterOrEqual asserts that the first element is greater than or equal to the second

assert.GreaterOrEqual(t, 2, 1)
assert.GreaterOrEqual(t, 2, 2)
assert.GreaterOrEqual(t, "b", "a")
assert.GreaterOrEqual(t, "b", "b")

func GreaterOrEqualf added in v1.4.0

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

GreaterOrEqualf asserts that the first element is greater than or equal to the second

assert.GreaterOrEqualf(t, 2, 1, "error message %s", "formatted")
assert.GreaterOrEqualf(t, 2, 2, "error message %s", "formatted")
assert.GreaterOrEqualf(t, "b", "a", "error message %s", "formatted")
assert.GreaterOrEqualf(t, "b", "b", "error message %s", "formatted")

func Greaterf added in v1.4.0

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

Greaterf asserts that the first element is greater than the second

assert.Greaterf(t, 2, 1, "error message %s", "formatted")
assert.Greaterf(t, float64(2), float64(1), "error message %s", "formatted")
assert.Greaterf(t, "b", "a", "error message %s", "formatted")

func HTTPBody

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

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

func HTTPBodyContains

func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool

HTTPBodyContains asserts that a specified handler returns a body that contains a string.

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

Returns whether the assertion was successful (true) or not (false).

func HTTPBodyContainsf added in v1.2.0

func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool

HTTPBodyContainsf asserts that a specified handler returns a body that contains a string.

assert.HTTPBodyContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted")

Returns whether the assertion was successful (true) or not (false).

func HTTPBodyNotContains

func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool

HTTPBodyNotContains asserts that a specified handler returns a body that does not contain a string.

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

Returns whether the assertion was successful (true) or not (false).

func HTTPBodyNotContainsf added in v1.2.0

func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool

HTTPBodyNotContainsf asserts that a specified handler returns a body that does not contain a string.

assert.HTTPBodyNotContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted")

Returns whether the assertion was successful (true) or not (false).

func HTTPError

func HTTPError(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool

HTTPError asserts that a specified handler returns an error status code.

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

Returns whether the assertion was successful (true) or not (false).

func HTTPErrorf added in v1.2.0

func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool

HTTPErrorf asserts that a specified handler returns an error status code.

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

Returns whether the assertion was successful (true) or not (false).

func HTTPRedirect

func HTTPRedirect(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool

HTTPRedirect asserts that a specified handler returns a redirect status code.

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

Returns whether the assertion was successful (true) or not (false).

func HTTPRedirectf added in v1.2.0

func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool

HTTPRedirectf asserts that a specified handler returns a redirect status code.

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

Returns whether the assertion was successful (true) or not (false).

func HTTPStatusCode added in v1.6.0

func HTTPStatusCode(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, statuscode int, msgAndArgs ...interface{}) bool

HTTPStatusCode asserts that a specified handler returns a specified status code.

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

Returns whether the assertion was successful (true) or not (false).

func HTTPStatusCodef added in v1.6.0

func HTTPStatusCodef(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msg string, args ...interface{}) bool

HTTPStatusCodef asserts that a specified handler returns a specified status code.

assert.HTTPStatusCodef(t, myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted")

Returns whether the assertion was successful (true) or not (false).

func HTTPSuccess

func HTTPSuccess(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool

HTTPSuccess asserts that a specified handler returns a success status code.

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

Returns whether the assertion was successful (true) or not (false).

func HTTPSuccessf added in v1.2.0

func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool

HTTPSuccessf asserts that a specified handler returns a success status code.

assert.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted")

Returns whether the assertion was successful (true) or not (false).

func Implements

func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool

Implements asserts that an object is implemented by the specified interface.

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

func Implementsf added in v1.2.0

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

Implementsf asserts that an object is implemented by the specified interface.

assert.Implementsf(t, (*MyInterface)(nil), new(MyObject), "error message %s", "formatted")

func InDelta

func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool

InDelta asserts that the two numerals are within delta of each other.

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

func InDeltaMapValues added in v1.2.0

func InDeltaMapValues(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool

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

func InDeltaMapValuesf added in v1.2.0

func InDeltaMapValuesf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool

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

func InDeltaSlice

func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool

InDeltaSlice is the same as InDelta, except it compares two slices.

func InDeltaSlicef added in v1.2.0

func InDeltaSlicef(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool