assert
v1.12.1
Documentation
pkg.go.dev ↗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.
Variables
AnError
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
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.
Condition
func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool
Condition uses a Comparison to assert a complex condition.
Conditionf
func Conditionf(t TestingT, comp Comparison, msg string, args ...interface{}) bool
Conditionf uses a Comparison to assert a complex condition.
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")
Containsf
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")
DirExists
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.
DirExistsf
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.
ElementsMatch
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])
ElementsMatchf
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")
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)
Emptyf
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")
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.
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)
EqualErrorf
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")
EqualExportedValues
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.
S
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
EqualExportedValuesf
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
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))
EqualValuesf
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")
Equalf
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.
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)
ErrorAs
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.
ErrorAsf
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.
ErrorContains
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)
ErrorContainsf
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")
ErrorIs
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.
ErrorIsf
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.
Errorf
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")
Eventually
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)
EventuallyWithT
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")
EventuallyWithTf
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")
Eventuallyf
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")
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))
Exactlyf
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")
Fail
func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool
Fail reports a failure through
FailNow
func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool
FailNow fails test
FailNowf
func FailNowf(t TestingT, failureMessage string, msg string, args ...interface{}) bool
FailNowf fails test
Failf
func Failf(t TestingT, failureMessage string, msg string, args ...interface{}) bool
Failf reports a failure through
False
func False(t TestingT, value bool, msgAndArgs ...interface{}) bool
False asserts that the specified value is false.
assert.False(t, myBool)