require
v1.12.1
Documentation
pkg.go.dev ↗Package require implements the same assertions as the assert package but stops test execution when a test fails.
Example Usage
The following is a complete example using require in a standard test function:
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestSomething(t *testing.T) {
var a string = "Hello"
var b string = "Hello"
require.Equal(t, a, b, "The two words should be the same.")
}
Assertions
The require package have same global functions as in the assert package, but instead of returning a boolean result they call testing.T.FailNow. A consequence of this is that it must be called from the goroutine running the test function, not from other goroutines created during the test.
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.
Functions
Condition
func Condition(t TestingT, comp assert.Comparison, msgAndArgs ...interface{})
Condition uses a Comparison to assert a complex condition.
Conditionf
func Conditionf(t TestingT, comp assert.Comparison, msg string, args ...interface{})
Conditionf uses a Comparison to assert a complex condition.
Contains
func Contains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{})
Contains asserts that the specified string, list(array, slice...) or map contains the specified substring or element.
require.Contains(t, "Hello World", "World")
require.Contains(t, ["Hello", "World"], "World")
require.Contains(t, {"Hello": "World"}, "Hello")
Containsf
func Containsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{})
Containsf asserts that the specified string, list(array, slice...) or map contains the specified substring or element.
require.Containsf(t, "Hello World", "World", "error message %s", "formatted")
require.Containsf(t, ["Hello", "World"], "World", "error message %s", "formatted")
require.Containsf(t, {"Hello": "World"}, "Hello", "error message %s", "formatted")
DirExists
func DirExists(t TestingT, path string, msgAndArgs ...interface{})
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{})
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 interface{}, listB interface{}, msgAndArgs ...interface{})
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.
require.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2])
ElementsMatchf
func ElementsMatchf(t TestingT, listA interface{}, listB interface{}, msg string, args ...interface{})
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.
require.ElementsMatchf(t, [1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted")
Empty
func Empty(t TestingT, object interface{}, msgAndArgs ...interface{})
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".
require.Empty(t, obj)
Emptyf
func Emptyf(t TestingT, object interface{}, msg string, args ...interface{})
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".
require.Emptyf(t, obj, "error message %s", "formatted")
Equal
func Equal(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{})
Equal asserts that two objects are equal.
require.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{})
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() require.EqualError(t, err, expectedErrorString)
EqualErrorf
func EqualErrorf(t TestingT, theError error, errString string, msg string, args ...interface{})
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() require.EqualErrorf(t, err, expectedErrorString, "error message %s", "formatted")
EqualExportedValues
func EqualExportedValues(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{})
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
}
require.EqualExportedValues(t, S{1, 2}, S{1, 3}) => true
require.EqualExportedValues(t, S{1, 2}, S{2, 3}) => false
EqualExportedValuesf
func EqualExportedValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{})
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
}
require.EqualExportedValuesf(t, S{1, 2}, S{1, 3}, "error message %s", "formatted") => true
require.EqualExportedValuesf(t, S{1, 2}, S{2, 3}, "error message %s", "formatted") => false
EqualValues
func EqualValues(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{})
EqualValues asserts that two objects are equal or convertible to the larger type and equal.
require.EqualValues(t, uint32(123), int32(123))
EqualValuesf
func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{})
EqualValuesf asserts that two objects are equal or convertible to the larger type and equal.
require.EqualValuesf(t, uint32(123), int32(123), "error message %s", "formatted")
Equalf
func Equalf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{})
Equalf asserts that two objects are equal.
require.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{})
Error asserts that a function returned a non-nil error (ie. an error).
actualObj, err := SomeFunction() require.Error(t, err)
ErrorAs
func ErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interface{})
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{})
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{})
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() require.ErrorContains(t, err, expectedErrorSubString)
ErrorContainsf
func ErrorContainsf(t TestingT, theError error, contains string, msg string, args ...interface{})
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() require.ErrorContainsf(t, err, expectedErrorSubString, "error message %s", "formatted")
ErrorIs
func ErrorIs(t TestingT, err error, target error, msgAndArgs ...interface{})
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{})
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{})
Errorf asserts that a function returned a non-nil error (ie. an error).
actualObj, err := SomeFunction() require.Errorf(t, err, "error message %s", "formatted")
Eventually
func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{})
Eventually asserts that given condition will be met in waitFor time, periodically checking target function each tick.
require.Eventually(t, func() bool { return true; }, time.Second, 10*time.Millisecond)
EventuallyWithT
func EventuallyWithT(t TestingT, condition func(collect *assert.CollectT), waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{})
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
}()
require.EventuallyWithT(t, func(c *assert.CollectT) {
// add assertions as needed; any assertion failure will fail the current tick
require.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 *assert.CollectT), waitFor time.Duration, tick time.Duration, msg string, args ...interface{})
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
}()
require.EventuallyWithTf(t, func(c *assert.CollectT) {
// add assertions as needed; any assertion failure will fail the current tick
require.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{})
Eventuallyf asserts that given condition will be met in waitFor time, periodically checking target function each tick.
require.Eventuallyf(t, func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted")
Exactly
func Exactly(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{})
Exactly asserts that two objects are equal in value and type.
require.Exactly(t, int32(123), int64(123))
Exactlyf
func Exactlyf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{})
Exactlyf asserts that two objects are equal in value and type.
require.Exactlyf(t, int32(123), int64(123), "error message %s", "formatted")
Fail
func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{})
Fail reports a failure through
FailNow
func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{})
FailNow fails test
FailNowf
func FailNowf(t TestingT, failureMessage string, msg string, args ...interface{})
FailNowf fails test
Failf
func Failf(t TestingT, failureMessage string, msg string, args ...interface{})
Failf reports a failure through
False
func False(t TestingT, value bool, msgAndArgs ...interface{})
False asserts that the specified value is false.
require.False(t, myBool)
Falsef
func Falsef(t TestingT, value bool, msg string, args ...interface{})
Falsef asserts that the specified value is false.
require.Falsef(t, myBool, "error message %s", "formatted")
FileExists
func FileExists(t TestingT, path string, msgAndArgs ...interface{})
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.