### Basic Test Suite Example Source: https://pkg.go.dev/github.com/stretchr/testify Demonstrates how to define a testing suite using the `suite` package. Includes setup and test methods. Use this for structured testing with setup and teardown logic. ```go // Basic imports import ( t"testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" ) // Define the suite, and absorb the built-in basic suite // functionality from testify - including a T() method which // returns the current testing context type ExampleTestSuite struct { suite.Suite VariableThatShouldStartAtFive int } // Make sure that VariableThatShouldStartAtFive is set to five // before each test func (suite *ExampleTestSuite) SetupTest() { suite.VariableThatShouldStartAtFive = 5 } // All methods that begin with "Test" are run as tests within a // suite. func (suite *ExampleTestSuite) TestExample() { assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive) } // In order for 'go test' to run this suite, we need to create // a normal test function and pass our suite to suite.Run func TestExampleTestSuite(t *testing.T) { suite.Run(t, new(ExampleTestSuite)) } ``` -------------------------------- ### Install Testify using go get Source: https://pkg.go.dev/github.com/stretchr/testify Command to install the Testify library. Run this in your terminal to add Testify to your Go project. ```bash go get github.com/stretchr/testify ``` -------------------------------- ### Define and Run a Test Suite in Go Source: https://pkg.go.dev/github.com/stretchr/testify/suite This example demonstrates how to define a testing suite by extending suite.Suite, implementing setup methods, and running the suite using suite.Run. Ensure your test function signature matches what 'go test' expects. ```go import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" ) // Define the suite, and absorb the built-in basic suite // functionality from testify - including a T() method which // returns the current testing context type ExampleTestSuite struct { suite.Suite VariableThatShouldStartAtFive int } // Make sure that VariableThatShouldStartAtFive is set to five // before each test func (suite *ExampleTestSuite) SetupTest() { suite.VariableThatShouldStartAtFive = 5 } // All methods that begin with "Test" are run as tests within a // suite. func (suite *ExampleTestSuite) TestExample() { assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive) suite.Equal(5, suite.VariableThatShouldStartAtFive) } // In order for 'go test' to run this suite, we need to create // a normal test function and pass our suite to suite.Run func TestExampleTestSuite(t *testing.T) { suite.Run(t, new(ExampleTestSuite)) } ``` -------------------------------- ### suite.SetupSubTest Interface Source: https://pkg.go.dev/github.com/stretchr/testify/suite Interface for defining a setup method that runs before each subtest. ```APIDOC ## type SetupSubTest ### Description SetupSubTest has a SetupSubTest method, which will run before each subtest in the suite. ### Interface Definition ```go type SetupSubTest interface { SetupSubTest() } ``` ``` -------------------------------- ### Import assert package Source: https://pkg.go.dev/github.com/stretchr/testify Example of how to import and use the `assert` package in your Go test files. This is a common starting point for using Testify's assertion functions. ```go package yours import ( "testing" "github.com/stretchr/testify/assert" ) func TestSomething(t *testing.T) { assert.True(t, true, "True is true!") } ``` -------------------------------- ### suite.SetupAllSuite Interface Source: https://pkg.go.dev/github.com/stretchr/testify/suite Interface for defining a setup method that runs once before all tests in the suite. ```APIDOC ## type SetupAllSuite ### Description SetupAllSuite has a SetupSuite method, which will run before the tests in the suite are run. ### Interface Definition ```go type SetupAllSuite interface { SetupSuite() } ``` ``` -------------------------------- ### suite.SetupTestSuite Interface Source: https://pkg.go.dev/github.com/stretchr/testify/suite Interface for defining a setup method that runs before each test in the suite. ```APIDOC ## type SetupTestSuite ### Description SetupTestSuite has a SetupTest method, which will run before each test in the suite. ### Interface Definition ```go type SetupTestSuite interface { SetupTest() } ``` ``` -------------------------------- ### On Source: https://pkg.go.dev/github.com/stretchr/testify/mock Starts the description of an expected method call. It takes the method name and any arguments that are expected to be passed to it. ```APIDOC ## On ### Description Defines an expectation for a specific method call, including the method name and expected arguments. Returns a `*Call` object that can be further configured with `Return`. ### Method func (*Mock) On(methodName string, arguments ...interface{}) *Call ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go Mock.On("MyMethod", arg1, arg2) ``` ### Response #### Success Response (*Call) - **0*Call**: A pointer to a Call object representing the expectation, which can be chained with `Return`. #### Response Example None ``` -------------------------------- ### SetupTestSuite Interface for Test Setup Source: https://pkg.go.dev/github.com/stretchr/testify/suite The SetupTestSuite interface provides a SetupTest method that is executed before each individual test method within the suite. Use this for setting up test-specific preconditions. ```go type SetupTestSuite interface { SetupTest() } ``` -------------------------------- ### SetupAllSuite Interface for Suite Setup Source: https://pkg.go.dev/github.com/stretchr/testify/suite The SetupAllSuite interface defines a SetupSuite method that runs once before any tests in the suite are executed. This is useful for initializing resources required for the entire test suite. ```go type SetupAllSuite interface { SetupSuite() } ``` -------------------------------- ### Require Positive Examples Source: https://pkg.go.dev/github.com/stretchr/testify/require Asserts that the specified element is positive. ```go require.Positive(t, 1) ``` ```go require.Positive(t, 1.23) ``` -------------------------------- ### SetupSubTest Interface for Subtest Setup Source: https://pkg.go.dev/github.com/stretchr/testify/suite Implement the SetupSubTest interface to define a method that runs before each subtest within a suite. This is useful for setting up state specific to individual subtests. ```go type SetupSubTest interface { SetupSubTest() } ``` -------------------------------- ### Basic Assertion Example Source: https://pkg.go.dev/github.com/stretchr/testify/assert Demonstrates a simple assertion using assert.Equal within a standard Go test function. Ensure the 'github.com/stretchr/testify/assert' package is imported. ```go 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.") } ``` -------------------------------- ### Example Usage of Require in a Test Source: https://pkg.go.dev/github.com/stretchr/testify/require Demonstrates how to use the require package within a standard Go test function. Imports are necessary for testing and the require package. ```go 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.") } ``` -------------------------------- ### Require Positivef Examples Source: https://pkg.go.dev/github.com/stretchr/testify/require Asserts that the specified element is positive, with formatted error messages. ```go require.Positivef(t, 1, "error message %s", "formatted") ``` ```go require.Positivef(t, 1.23, "error message %s", "formatted") ``` -------------------------------- ### Chained Assertions Example Source: https://pkg.go.dev/github.com/stretchr/testify/assert Shows how to use chained assertions by creating an assert instance with assert.New(t). This format is useful when performing multiple assertions within a single test function. ```go 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.") } ``` -------------------------------- ### Require Panicsf Example Source: https://pkg.go.dev/github.com/stretchr/testify/require Asserts that the code inside the specified PanicTestFunc panics, with formatted error messages. ```go require.Panicsf(t, func(){ GoCrazy() }, "error message %s", "formatted") ``` -------------------------------- ### Require Panics Example Source: https://pkg.go.dev/github.com/stretchr/testify/require Asserts that the code inside the specified PanicTestFunc panics. ```go require.Panics(t, func(){ GoCrazy() }) ``` -------------------------------- ### Require NotSamef Example Source: https://pkg.go.dev/github.com/stretchr/testify/require Asserts that two pointers do not reference the same object. Both arguments must be pointer variables. ```go require.NotSamef(t, ptr1, ptr2, "error message %s", "formatted") ``` -------------------------------- ### Require NotSubsetf Examples Source: https://pkg.go.dev/github.com/stretchr/testify/require Asserts that a list (array, slice, or map) does NOT contain all elements given in the subset (array, slice, or map), with formatted error messages. Map elements are key-value pairs unless compared with an array or slice where only the map key is evaluated. ```go require.NotSubsetf(t, [1, 3, 4], [1, 2], "error message %s", "formatted") ``` ```go require.NotSubsetf(t, {"x": 1, "y": 2}, {"z": 3}, "error message %s", "formatted") ``` ```go require.NotSubsetf(t, [1, 3, 4], {1: "one", 2: "two"}, "error message %s", "formatted") ``` ```go require.NotSubsetf(t, {"x": 1, "y": 2}, ["z"], "error message %s", "formatted") ``` -------------------------------- ### Require PanicsWithValuef Example Source: https://pkg.go.dev/github.com/stretchr/testify/require Asserts that the code inside the specified PanicTestFunc panics, and that the recovered panic value equals the expected panic value, with formatted error messages. ```go require.PanicsWithValuef(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") ``` -------------------------------- ### Require PanicsWithErrorf Example Source: https://pkg.go.dev/github.com/stretchr/testify/require Asserts that the code inside the specified PanicTestFunc panics, and that the recovered panic value is an error that satisfies the EqualError comparison, with formatted error messages. ```go require.PanicsWithErrorf(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") ``` -------------------------------- ### Require NotSubset Examples Source: https://pkg.go.dev/github.com/stretchr/testify/require Asserts that a list (array, slice, or map) does NOT contain 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. ```go require.NotSubset(t, [1, 3, 4], [1, 2]) ``` ```go require.NotSubset(t, {"x": 1, "y": 2}, {"z": 3}) ``` ```go require.NotSubset(t, [1, 3, 4], {1: "one", 2: "two"}) ``` ```go require.NotSubset(t, {"x": 1, "y": 2}, ["z"]) ``` -------------------------------- ### func (Arguments) Is Source: https://pkg.go.dev/github.com/stretchr/testify/mock Is gets whether the objects match the arguments specified. ```APIDOC ## func (Arguments) Is ### Description Is gets whether the objects match the arguments specified. ### Signature ```go func (args Arguments) Is(objects ...interface{}) bool ``` ### Parameters #### Path Parameters - **objects** ([]interface{}) - Required - The objects to check for a match. ### Returns - **bool** - True if the objects match the arguments, false otherwise. ``` -------------------------------- ### ObjectsAreEqualValues Source: https://pkg.go.dev/github.com/stretchr/testify/assert ObjectsAreEqualValues gets whether two objects are equal, or if their values are equal. ```APIDOC ## ObjectsAreEqualValues ### Description ObjectsAreEqualValues gets whether two objects are equal, or if their values are equal. ### Signature ```go func ObjectsAreEqualValues(expected, actual interface{}) bool ``` ``` -------------------------------- ### Require Method Source: https://pkg.go.dev/github.com/stretchr/testify/suite Retrieves the require context for the suite. ```go func (suite *Suite) Require() *require.Assertions ``` -------------------------------- ### On Method Source: https://pkg.go.dev/github.com/stretchr/testify/mock Initiates the definition of an expected method call. Use this to specify which method is expected and its arguments. ```go func (m *Mock) On(methodName string, arguments ...interface{}) *Call ``` ```go Mock.On("MyMethod", arg1, arg2) ``` -------------------------------- ### Basic Assertions with testify/assert Source: https://pkg.go.dev/github.com/stretchr/testify Use the `assert` package for standard assertions. Each function takes `testing.T` and returns a boolean indicating success. This allows for conditional further assertions. ```go package yours import ( testing "github.com/stretchr/testify/assert" ) func TestSomething(t *testing.T) { // assert equality assert.Equal(t, 123, 123, "they should be equal") // assert inequality assert.NotEqual(t, 123, 456, "they should not be equal") // assert for nil (good for errors) assert.Nil(t, object) // assert for not nil (good when you expect something) if assert.NotNil(t, object) { // now we know that object isn't nil, we are safe to make // further assertions without causing any errors assert.Equal(t, "Something", object.Value) } } ``` -------------------------------- ### Suite.SetS Source: https://pkg.go.dev/github.com/stretchr/testify/suite SetS needs to set the current test suite as parent to get access to the parent methods. ```APIDOC ## func (*Suite) SetS ```go func (suite *Suite) SetS(s TestingSuite) ``` SetS needs to set the current test suite as parent to get access to the parent methods. ``` -------------------------------- ### WithinRange Source: https://pkg.go.dev/github.com/stretchr/testify/assert WithinRange asserts that the actual time falls within the specified start and end times (inclusive). ```APIDOC ## WithinRange ### Description Asserts that the actual time falls within the specified start and end times (inclusive). ### Signature func (a *Assertions) WithinRange(actual time.Time, start time.Time, end time.Time, msgAndArgs ...interface{}) bool ``` -------------------------------- ### Use Mock Placeholders for Dynamic Arguments in Go Source: https://pkg.go.dev/github.com/stretchr/testify Demonstrates using `mock.Anything` to set expectations when the arguments are dynamic or unpredictable. This is useful for arguments like timestamps or hashes that cannot be known in advance. ```go package yours import ( test_ "testing" "github.com/stretchr/testify/mock" ) /* Test objects */ // MyMockedObject is a mocked object that implements an interface // that describes an object that the code I am testing relies on. type MyMockedObject struct { mock.Mock } // DoSomething is a method on MyMockedObject that implements some interface // and just records the activity, and returns what the Mock object tells it to. // // In the real object, this method would do something useful, but since this // is a mocked object - we're just going to stub it out. // // NOTE: This method is not being tested here, code that uses this object is. func (m *MyMockedObject) DoSomething(number int) (bool, error) { args := m.Called(number) return args.Bool(0), args.Error(1) } /* Actual test functions */ // TestSomethingWithPlaceholder is a second example of how to use our test object to // make assertions about some target code we are testing. // This time using a placeholder. Placeholders might be used when the // data being passed in is normally dynamically generated and cannot be // predicted beforehand (eg. containing hashes that are time sensitive) func TestSomethingWithPlaceholder(t *testing.T) { // create an instance of our test object testObj := new(MyMockedObject) // set up expectations with a placeholder in the argument list testObj.On("DoSomething", mock.Anything).Return(true, nil) // call the code we are testing targetFuncThatDoesSomethingWithObj(testObj) // assert that the expectations were met testObj.AssertExpectations(t) } // targetFuncThatDoesSomethingWithObj is a placeholder for the actual function being tested. // It is assumed to call the DoSomething method on the provided object. func targetFuncThatDoesSomethingWithObj(obj *MyMockedObject) { // This is a placeholder for the actual function logic. // In a real scenario, this function would interact with the obj. obj.DoSomething(123) // The argument here will match mock.Anything } ``` -------------------------------- ### AssertExpectations Method Source: https://pkg.go.dev/github.com/stretchr/testify/mock Verifies that all methods set up with On and Return were indeed called as expected. The order of calls does not matter. ```go func (m *Mock) AssertExpectations(t TestingT) bool ``` -------------------------------- ### Check if Objects Are Equal by Value Source: https://pkg.go.dev/github.com/stretchr/testify/assert ObjectsAreEqualValues gets whether two objects are equal, or if their values are equal. This function does not perform assertions. ```go func ObjectsAreEqualValues(expected, actual interface{}) bool ``` -------------------------------- ### Assert WithinRange Source: https://pkg.go.dev/github.com/stretchr/testify/assert Asserts that a given time.Time value falls within a specified inclusive time range (start and end times). ```go assert.WithinRange(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second)) ``` -------------------------------- ### Suite.T Source: https://pkg.go.dev/github.com/stretchr/testify/suite T retrieves the current *testing.T context. ```APIDOC ## func (*Suite) T ```go func (suite *Suite) T() *testing.T ``` T retrieves the current *testing.T context. ``` -------------------------------- ### WithinRangef Source: https://pkg.go.dev/github.com/stretchr/testify/assert WithinRangef asserts that the actual time falls within the specified start and end times (inclusive), formatting the error message. ```APIDOC ## WithinRangef ### Description Asserts that the actual time falls within the specified start and end times (inclusive), formatting the error message. ### Signature func (a *Assertions) WithinRangef(actual time.Time, start time.Time, end time.Time, msg string, args ...interface{}) bool ``` -------------------------------- ### T Method Source: https://pkg.go.dev/github.com/stretchr/testify/suite Retrieves the current *testing.T context. ```go func (suite *Suite) T() *testing.T ``` -------------------------------- ### Require PanicsWithValue Example Source: https://pkg.go.dev/github.com/stretchr/testify/require Asserts that the code inside the specified PanicTestFunc panics, and that the recovered panic value equals the expected panic value. ```go require.PanicsWithValue(t, "crazy error", func(){ GoCrazy() }) ``` -------------------------------- ### Checking Linked YAML Implementation Source: https://pkg.go.dev/github.com/stretchr/testify/assert/yaml Shows how to use 'go list' to verify which YAML unmarshalling implementation is currently linked. This helps in debugging or confirming build tag usage. ```bash go list -f '{{.Imports}}' github.com/stretchr/testify/assert/yaml ``` ```bash go list -tags testify_yaml_fail -f '{{.Imports}}' github.com/stretchr/testify/assert/yaml ``` ```bash go list -tags testify_yaml_custom -f '{{.Imports}}' github.com/stretchr/testify/assert/yaml ``` -------------------------------- ### Build Tag Usage for YAML Source: https://pkg.go.dev/github.com/stretchr/testify/assert/yaml Demonstrates how to use build tags to select alternative YAML unmarshalling implementations. Use 'go test -tags ' to activate. ```bash go test -tags testify_yaml_fail ``` -------------------------------- ### Require PanicsWithError Example Source: https://pkg.go.dev/github.com/stretchr/testify/require Asserts that the code inside the specified PanicTestFunc panics, and that the recovered panic value is an error that satisfies the EqualError comparison. ```go require.PanicsWithError(t, "crazy error", func(){ GoCrazy() }) ``` -------------------------------- ### Run a Testing Suite in Go Source: https://pkg.go.dev/github.com/stretchr/testify/suite The Run function from the suite package executes all tests within a provided testing suite. It requires a standard *testing.T object and an instance of a type that implements the TestingSuite interface. ```go func Run(t *testing.T, suite TestingSuite) ``` -------------------------------- ### func (Arguments) Diff Source: https://pkg.go.dev/github.com/stretchr/testify/mock Diff gets a string describing the differences between the arguments and the specified objects. It returns the diff string and the number of differences found. ```APIDOC ## func (Arguments) Diff ### Description Diff gets a string describing the differences between the arguments and the specified objects. Returns the diff string and number of differences found. ### Signature ```go func (args Arguments) Diff(objects []interface{}) (string, int) ``` ### Parameters #### Path Parameters - **objects** ([]interface{}) - Required - The objects to compare against. ### Returns - **string** - A string describing the differences. - **int** - The number of differences found. ``` -------------------------------- ### Define and Use a Mock Object in Go Source: https://pkg.go.dev/github.com/stretchr/testify Defines a mock object and demonstrates setting expectations with specific arguments. Use this when the arguments passed to the mocked method are predictable. ```go package yours import ( test_ "testing" "github.com/stretchr/testify/mock" ) /* Test objects */ // MyMockedObject is a mocked object that implements an interface // that describes an object that the code I am testing relies on. type MyMockedObject struct { mock.Mock } // DoSomething is a method on MyMockedObject that implements some interface // and just records the activity, and returns what the Mock object tells it to. // // In the real object, this method would do something useful, but since this // is a mocked object - we're just going to stub it out. // // NOTE: This method is not being tested here, code that uses this object is. func (m *MyMockedObject) DoSomething(number int) (bool, error) { args := m.Called(number) return args.Bool(0), args.Error(1) } /* Actual test functions */ // TestSomething is an example of how to use our test object to // make assertions about some target code we are testing. func TestSomething(t *testing.T) { // create an instance of our test object testObj := new(MyMockedObject) // set up expectations testObj.On("DoSomething", 123).Return(true, nil) // call the code we are testing targetFuncThatDoesSomethingWithObj(testObj) // assert that the expectations were met testObj.AssertExpectations(t) } // targetFuncThatDoesSomethingWithObj is a placeholder for the actual function being tested. // It is assumed to call the DoSomething method on the provided object. func targetFuncThatDoesSomethingWithObj(obj *MyMockedObject) { // This is a placeholder for the actual function logic. // In a real scenario, this function would interact with the obj. obj.DoSomething(123) } ``` -------------------------------- ### Suite.Require Source: https://pkg.go.dev/github.com/stretchr/testify/suite Require returns a require context for suite. ```APIDOC ## func (*Suite) Require ```go func (suite *Suite) Require() *require.Assertions ``` Require returns a require context for suite. ``` -------------------------------- ### SetT Method Source: https://pkg.go.dev/github.com/stretchr/testify/suite Sets the current *testing.T context. ```go func (suite *Suite) SetT(t *testing.T) ``` -------------------------------- ### Check Directory Existence with require.DirExists Source: https://pkg.go.dev/github.com/stretchr/testify/require Use DirExists to verify if a directory exists at the given path. It also fails if the path points to a file or if there's an error checking existence. Execution halts on failure. ```go func DirExists(t TestingT, path string, msgAndArgs ...interface{}) ``` -------------------------------- ### New Function Definition Source: https://pkg.go.dev/github.com/stretchr/testify/_codegen/internal/imports Initializes a new Importer to track packages imported by a given package. ```go func New(currentpkg string) Importer ``` -------------------------------- ### Suite Source: https://pkg.go.dev/github.com/stretchr/testify/suite Suite is a basic testing suite with methods for storing and retrieving the current *testing.T context. ```APIDOC ## type Suite ```go type Suite struct { *assert.Assertions // contains filtered or unexported fields } ``` Suite is a basic testing suite with methods for storing and retrieving the current *testing.T context. ``` -------------------------------- ### BeforeTest Interface for Pre-Test Execution Source: https://pkg.go.dev/github.com/stretchr/testify/suite Implement the BeforeTest interface to define a method that executes just before each test in a suite begins. The method is provided with the suite name and the test name. ```go type BeforeTest interface { BeforeTest(suiteName, testName string) } ``` -------------------------------- ### Assert Time Within Range Source: https://pkg.go.dev/github.com/stretchr/testify/require Use WithinRange to assert that an actual time falls inclusively within a specified start and end time. This is helpful for validating events or schedules. ```go require.WithinRange(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second)) ``` -------------------------------- ### YAMLEqf: Assert YAML Equality with Formatting Source: https://pkg.go.dev/github.com/stretchr/testify/assert Asserts that two YAML strings are equivalent, allowing for formatted error messages. Use this for more control over assertion failure messages. ```go func (a *Assertions) YAMLEqf(expected string, actual string, msg string, args ...interface{}) bool ``` -------------------------------- ### Assert Within Time Range Source: https://pkg.go.dev/github.com/stretchr/testify/assert Use WithinRange to assert that a time.Time value falls inclusively within a specified start and end time. Optional additional arguments can format a custom error message. ```go a.WithinRange(time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second)) ``` -------------------------------- ### DirExistsf Source: https://pkg.go.dev/github.com/stretchr/testify/assert DirExistsf asserts that a directory exists at the given path, with formatted failure messages. It takes a TestingT, the path, a message format string, and arguments. ```APIDOC ## func DirExistsf(t TestingT, path string, msg string, args ...interface{}) bool ### Description DirExistsf asserts that a directory exists at the given path, with formatted failure messages. It takes a TestingT, the path, a message format string, and arguments. ### Parameters - **t** (TestingT) - The testing object. - **path** (string) - The path to the directory. - **msg** (string) - The format string for the failure message. - **args** (...interface{}) - Arguments for the format string. ``` -------------------------------- ### On Source: https://pkg.go.dev/github.com/stretchr/testify/mock On chains a new expectation description onto the mocked interface. This allows syntax like. ```APIDOC ## func (*Call) On ### Description On chains a new expectation description onto the mocked interface. This allows syntax like. ### Method *Call ### Endpoint On(methodName string, arguments ...interface{}) ### Parameters - **methodName** (string) - The name of the method to mock. - **arguments** (...interface{}) - The arguments to match for the method call. ### Request Example ```go Mock. On("MyMethod", 1).Return(nil). On("MyOtherMethod", 'a', 'b', 'c').Return(errors.New("Some Error")) ``` ### Response #### Success Response (200) - *Call - The modified Call object for chaining. #### Response Example None ``` -------------------------------- ### Suite.Assert Source: https://pkg.go.dev/github.com/stretchr/testify/suite Assert returns an assert context for suite. Normally, you can call `suite.NoError(expected, actual)`, but for situations where the embedded methods are overridden (for example, you might want to override assert.Assertions with require.Assertions), this method is provided so you can call `suite.Assert().NoError()`. ```APIDOC ## func (*Suite) Assert ```go func (suite *Suite) Assert() *assert.Assertions ``` Assert returns an assert context for suite. Normally, you can call `suite.NoError(expected, actual)`, but for situations where the embedded methods are overridden (for example, you might want to override assert.Assertions with require.Assertions), this method is provided so you can call `suite.Assert().NoError()`. ``` -------------------------------- ### Assert Same Pointer Reference Source: https://pkg.go.dev/github.com/stretchr/testify/assert Use Same to assert that two variables point to the exact same memory address. Both arguments must be pointer variables. ```go assert.Same(t, ptr1, ptr2) ``` -------------------------------- ### Zerof: Assert Zero Value with Formatting Source: https://pkg.go.dev/github.com/stretchr/testify/assert Asserts that a given value is the zero value for its type, with support for formatted error messages. Use this for detailed failure reporting. ```go func (a *Assertions) Zerof(i interface{}, msg string, args ...interface{}) bool ``` -------------------------------- ### Same Source: https://pkg.go.dev/github.com/stretchr/testify/assert Same asserts that two pointers reference the exact same object. Both arguments must be pointer variables. ```APIDOC ## Same ### Description Same asserts that two pointers reference the same object. ### Signature ```go func (a *Assertions) Same(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool ``` ### Details Both arguments must be pointer variables. Pointer variable sameness is determined based on the equality of both type and value. ### Example ```go a.Same(ptr1, ptr2) ``` ``` -------------------------------- ### Assert Equality of Values with require.Equal Source: https://pkg.go.dev/github.com/stretchr/testify/require Use Equal to assert that two values are equal. For pointers, it compares the referenced values. Function equality cannot be determined and will always fail. Execution halts on failure. ```go require.Equal(t, 123, 123) ``` -------------------------------- ### FileExistsf Source: https://pkg.go.dev/github.com/stretchr/testify/assert FileExistsf asserts that a file exists at the given path, with formatted failure messages. It takes a TestingT, the path, a message format string, and arguments. ```APIDOC ## func FileExistsf(t TestingT, path string, msg string, args ...interface{}) bool ### Description FileExistsf asserts that a file exists at the given path, with formatted failure messages. It takes a TestingT, the path, a message format string, and arguments. ### Parameters - **t** (TestingT) - The testing object. - **path** (string) - The path to the file. - **msg** (string) - The format string for the failure message. - **args** (...interface{}) - Arguments for the format string. ``` -------------------------------- ### String Method Source: https://pkg.go.dev/github.com/stretchr/testify/mock Provides a %v format string for the Mock object, useful for debugging. This method is implicitly used by Arguments.Diff when a Mock is passed and helps avoid race conditions during default %v formatting. ```go func (m *Mock) String() string ``` -------------------------------- ### DirExists Source: https://pkg.go.dev/github.com/stretchr/testify/assert DirExists asserts that a directory exists at the given path. It takes a TestingT, the path, and optional message arguments. ```APIDOC ## func DirExists(t TestingT, path string, msgAndArgs ...interface{}) bool ### Description DirExists asserts that a directory exists at the given path. It takes a TestingT, the path, and optional message arguments. ### Parameters - **t** (TestingT) - The testing object. - **path** (string) - The path to the directory. - **msgAndArgs** (...interface{}) - Optional message and arguments for failure reporting. ``` -------------------------------- ### Configure Call Delay with After Source: https://pkg.go.dev/github.com/stretchr/testify/mock Use the After method on a Call to introduce a delay before the mock method returns. This simulates network latency or other time-dependent behaviors. ```go func (c *Call) After(d time.Duration) *Call ``` ```go Mock.On("MyMethod", arg1, arg2).After(time.Second) ``` -------------------------------- ### Suite.Run Source: https://pkg.go.dev/github.com/stretchr/testify/suite Run provides suite functionality around golang subtests. It should be called in place of t.Run(name, func(t *testing.T)) in test suite code. The passed-in func will be executed as a subtest with a fresh instance of t. Provides compatibility with go test pkg -run TestSuite/TestName/SubTestName. ```APIDOC ## func (*Suite) Run ```go func (suite *Suite) Run(name string, subtest func()) bool ``` Run provides suite functionality around golang subtests. It should be called in place of t.Run(name, func(t *testing.T)) in test suite code. The passed-in func will be executed as a subtest with a fresh instance of t. Provides compatibility with go test pkg -run TestSuite/TestName/SubTestName. ``` -------------------------------- ### FileExists: Check if a file exists at the given path Source: https://pkg.go.dev/github.com/stretchr/testify/assert Use FileExists to verify that a file exists at the specified path. The assertion fails if the path points to a directory or if there's an error checking the file's existence. ```go a.FileExists(path, msgAndArgs...) ``` -------------------------------- ### DirExistsf Source: https://pkg.go.dev/github.com/stretchr/testify/assert DirExistsf asserts that a directory exists at the given path, with support for formatted error messages. ```APIDOC ## DirExistsf ### Description Asserts that a directory exists at the given path. Formatted error message is supported. ### Signature func (a *Assertions) DirExistsf(path string, msg string, args ...interface{}) bool ``` -------------------------------- ### NotEqualf - Assert values are not equal (formatted message) Source: https://pkg.go.dev/github.com/stretchr/testify/require Use NotEqualf to assert that two values are not equal, with support for formatted error messages. It compares referenced values. ```go func (a *Assertions) NotEqualf(expected interface{}, actual interface{}, msg string, args ...interface{}) ``` ```go a.NotEqualf(obj1, obj2, "error message %s", "formatted") ``` -------------------------------- ### Assert Same Pointer with Formatting Source: https://pkg.go.dev/github.com/stretchr/testify/assert Use Samef to assert that two pointer variables reference the exact same object, with support for formatted error messages. Both arguments must be pointers. ```go a.Samef(ptr1, ptr2, "error message %s", "formatted") ``` -------------------------------- ### SetS Method Source: https://pkg.go.dev/github.com/stretchr/testify/suite Sets the current test suite as the parent to gain access to parent methods. Added in v1.8.2. ```go func (suite *Suite) SetS(s TestingSuite) ``` -------------------------------- ### TestingSuite Interface Source: https://pkg.go.dev/github.com/stretchr/testify/suite Defines methods for managing the current *testing.T context within a test suite. ```go type TestingSuite interface { T() *testing.T SetT(*testing.T) SetS(suite TestingSuite) } ``` -------------------------------- ### Assert HTTP Success Status with Formatting Source: https://pkg.go.dev/github.com/stretchr/testify/require Use HTTPSuccessf for asserting success status codes with formatted error messages. This allows for more descriptive success-related error reporting. ```go func (a *Assertions) HTTPSuccessf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) ``` ```go a.HTTPSuccessf(myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") ``` -------------------------------- ### Check if File Does Not Exist (Formatted) Source: https://pkg.go.dev/github.com/stretchr/testify/assert Use NoFileExistsf to assert that a given path does not point to an existing file, with support for formatted messages. This is helpful for providing specific failure details. ```go func (a *Assertions) NoFileExistsf(path string, msg string, args ...interface{}) bool ``` -------------------------------- ### Test Suite with Assertion Methods Source: https://pkg.go.dev/github.com/stretchr/testify Shows a testing suite where assertion methods are called directly on the suite object. This is an alternative to using the `assert` package directly within suite methods. ```go // Basic imports import ( "testing" "github.com/stretchr/testify/suite" ) // Define the suite, and absorb the built-in basic suite // functionality from testify - including assertion methods. type ExampleTestSuite struct { suite.Suite VariableThatShouldStartAtFive int } // Make sure that VariableThatShouldStartAtFive is set to five // before each test func (suite *ExampleTestSuite) SetupTest() { suite.VariableThatShouldStartAtFive = 5 } // All methods that begin with "Test" are run as tests within a // suite. func (suite *ExampleTestSuite) TestExample() { suite.Equal(suite.VariableThatShouldStartAtFive, 5) } // In order for 'go test' to run this suite, we need to create // a normal test function and pass our suite to suite.Run func TestExampleTestSuite(t *testing.T) { suite.Run(t, new(ExampleTestSuite)) } ``` -------------------------------- ### TestingSuite Source: https://pkg.go.dev/github.com/stretchr/testify/suite TestingSuite can store and return the current *testing.T context generated by 'go test'. ```APIDOC ## type TestingSuite ```go type TestingSuite interface { T() *testing.T SetT(*testing.T) SetS(suite TestingSuite) } ``` TestingSuite can store and return the current *testing.T context generated by 'go test'. ``` -------------------------------- ### Assert Less Than or Equal To with Formatting Source: https://pkg.go.dev/github.com/stretchr/testify/assert Use LessOrEqualf for formatted error messages when asserting less than or equal to conditions. This enhances the clarity of failure reports. ```go assert.LessOrEqualf(t, 1, 2, "error message %s", "formatted") ``` ```go assert.LessOrEqualf(t, 2, 2, "error message %s", "formatted") ``` ```go assert.LessOrEqualf(t, "a", "b", "error message %s", "formatted") ``` ```go assert.LessOrEqualf(t, "b", "b", "error message %s", "formatted") ``` -------------------------------- ### Assert Same Pointer Reference with Formatting Source: https://pkg.go.dev/github.com/stretchr/testify/assert Use Samef to assert that two variables reference the same object, with support for formatted error messages. Both arguments must be pointers. ```go assert.Samef(t, ptr1, ptr2, "error message %s", "formatted") ``` -------------------------------- ### Check if Directory Does Not Exist (Formatted) Source: https://pkg.go.dev/github.com/stretchr/testify/assert Use NoDirExistsf to assert that a given path does not point to an existing directory. This is useful for ensuring cleanup operations or initial states. ```go func (a *Assertions) NoDirExistsf(path string, msg string, args ...interface{}) bool ``` -------------------------------- ### Run Subtest Source: https://pkg.go.dev/github.com/stretchr/testify/suite Provides suite functionality around Go subtests. Use this in place of t.Run for integrated suite behavior. ```go func (suite *Suite) Run(name string, subtest func()) bool ``` -------------------------------- ### New Function Source: https://pkg.go.dev/github.com/stretchr/testify/_codegen/internal/imports The New function initializes and returns a new Importer. ```APIDOC ## func New(currentpkg string) Importer ```go func New(currentpkg string) Importer ``` ### Description New initializes a new structure to track packages imported by the currentpkg. ### Parameters - **currentpkg** (string) - The package to track imports for. ``` -------------------------------- ### Assert Directory Existsf Source: https://pkg.go.dev/github.com/stretchr/testify/assert Asserts that a directory exists at the specified path, with formatted error messages. Use for detailed failure reporting. ```go a.DirExistsf(path, "error message %s", "formatted") ``` -------------------------------- ### Checking Directory Existence with Formatting Source: https://pkg.go.dev/github.com/stretchr/testify/assert DirExistsf checks whether a directory exists at the given path, with support for formatted error messages. It fails if the path is a file or if there's an error during the check. ```go func DirExistsf(t TestingT, path string, msg string, args ...interface{}) bool ``` -------------------------------- ### Return Source: https://pkg.go.dev/github.com/stretchr/testify/mock Return specifies the return arguments for the expectation. ```APIDOC ## func (*Call) Return ### Description Return specifies the return arguments for the expectation. ### Method *Call ### Endpoint Return(returnArguments ...interface{}) ### Parameters - **returnArguments** (...interface{}) - The arguments to be returned when the mock is called. ### Request Example ```go Mock.On("DoSomething").Return(errors.New("failed")) ``` ### Response #### Success Response (200) - *Call - The modified Call object for chaining. #### Response Example None ``` -------------------------------- ### Assert Value Emptiness with Formatted Message using require.Emptyf Source: https://pkg.go.dev/github.com/stretchr/testify/require Use Emptyf for formatted error messages when asserting that a value is 'empty'. This includes zero values, slices/maps/channels with zero length, and pointers to empty values. Execution halts on failure. ```go require.Emptyf(t, obj, "error message %s", "formatted") ``` -------------------------------- ### Assert Boolean True with Formatting Source: https://pkg.go.dev/github.com/stretchr/testify/assert Use Truef to assert that a boolean value is true, with support for formatted error messages. Useful for providing context on failure. ```go assert.Truef(t, myBool, "error message %s", "formatted") ``` -------------------------------- ### Execute Handler Function on Mock Call Source: https://pkg.go.dev/github.com/stretchr/testify/mock Use `Run` to set a handler function that will be executed before the mock returns. This is useful for side effects, like modifying arguments passed by pointer. ```go func (c *Call) Run(fn func(args Arguments)) *Call ``` ```go Mock.On("Unmarshal", AnythingOfType("*map[string]interface{}")).Return().Run(func(args Arguments) { arg := args.Get(0).(*map[string]interface{}) arg["foo"] = "bar" }) ``` -------------------------------- ### FileExists Source: https://pkg.go.dev/github.com/stretchr/testify/assert FileExists asserts that a file exists at the given path. It takes a TestingT, the path, and optional message arguments. ```APIDOC ## func FileExists(t TestingT, path string, msgAndArgs ...interface{}) bool ### Description FileExists asserts that a file exists at the given path. It takes a TestingT, the path, and optional message arguments. ### Parameters - **t** (TestingT) - The testing object. - **path** (string) - The path to the file. - **msgAndArgs** (...interface{}) - Optional message and arguments for failure reporting. ``` -------------------------------- ### AssertExpectations Source: https://pkg.go.dev/github.com/stretchr/testify/mock Asserts that all methods defined using On and Return were called exactly as specified. The order of calls does not matter. ```APIDOC ## AssertExpectations ### Description Asserts that all expectations set on the mock object have been met. This includes verifying that all methods specified with `On` and `Return` were indeed called. ### Method func (*Mock) AssertExpectations(t TestingT) bool ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (bool) - **true**: if all expectations were met. - **false**: if any expectation was not met. #### Response Example None ``` -------------------------------- ### Check if File Exists (Formatted) Source: https://pkg.go.dev/github.com/stretchr/testify/require Checks if a file exists at the given path. Fails if the path is a directory or if there's an error during the check. ```go func FileExistsf(t TestingT, path string, msg string, args ...interface{}) ``` -------------------------------- ### Negativef: Assert Negative Number with Formatting Source: https://pkg.go.dev/github.com/stretchr/testify/assert Use Negativef for asserting a negative number with formatted error messages. This allows for more descriptive failure notifications. ```go func (a *Assertions) Negativef(e interface{}, msg string, args ...interface{}) bool a.Negativef(-1, "error message %s", "formatted") a.Negativef(-1.23, "error message %s", "formatted") ``` -------------------------------- ### Assert FileExists Source: https://pkg.go.dev/github.com/stretchr/testify/assert Checks if a file exists at the given path. Fails if the path points to a directory or if there's an error during the check. -------------------------------- ### TearDownAllSuite Interface for Suite Teardown Source: https://pkg.go.dev/github.com/stretchr/testify/suite Implement the TearDownAllSuite interface to define a method that runs once after all tests in the suite have completed. This is useful for cleaning up resources allocated for the entire suite. ```go type TearDownAllSuite interface { TearDownSuite() } ``` -------------------------------- ### Assert Directory Exists Source: https://pkg.go.dev/github.com/stretchr/testify/assert Asserts that a directory exists at the specified path. Fails if the path is a file or if there's an error checking existence. ```go a.DirExists(path) ``` -------------------------------- ### Suite.SetT Source: https://pkg.go.dev/github.com/stretchr/testify/suite SetT sets the current *testing.T context. ```APIDOC ## func (*Suite) SetT ```go func (suite *Suite) SetT(t *testing.T) ``` SetT sets the current *testing.T context. ``` -------------------------------- ### Check Directory Existence with Formatted Message using require.DirExistsf Source: https://pkg.go.dev/github.com/stretchr/testify/require Use DirExistsf for formatted error messages when checking if a directory exists at the given path. It also fails if the path points to a file or if there's an error. Execution halts on failure. ```go func DirExistsf(t TestingT, path string, msg string, args ...interface{}) ``` -------------------------------- ### Require NoFileExistsf Function Signature Source: https://pkg.go.dev/github.com/stretchr/testify/require Checks if a file does not exist at the given path, with formatted error messages. Fails only if the path points to an existing file. ```go func NoFileExistsf(t TestingT, path string, msg string, args ...interface{}) ``` -------------------------------- ### LessOrEqualf: Assert Less Than or Equal To with Formatting Source: https://pkg.go.dev/github.com/stretchr/testify/assert Use LessOrEqualf for asserting less than or equal to conditions with formatted error messages. This allows for detailed failure reporting. ```go func (a *Assertions) LessOrEqualf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool a.LessOrEqualf(1, 2, "error message %s", "formatted") a.LessOrEqualf(2, 2, "error message %s", "formatted") a.LessOrEqualf("a", "b", "error message %s", "formatted") a.LessOrEqualf("b", "b", "error message %s", "formatted") ``` -------------------------------- ### Require Equalf for Formatted Value Equality Source: https://pkg.go.dev/github.com/stretchr/testify/require Use Equalf to assert that two values are equal, with a formatted error message on failure. It handles pointer equality by comparing referenced values. ```go require.Equalf(t, 123, 123, "error message %s", "formatted") ``` -------------------------------- ### Assert object does not implement an interface with formatting Source: https://pkg.go.dev/github.com/stretchr/testify/assert Use NotImplementsf for formatted error messages when asserting that an object does not implement a specified interface. This provides more detailed failure information. ```go a.NotImplementsf((*MyInterface)(nil), new(MyObject), "error message %s", "formatted") ``` -------------------------------- ### WithStats Interface Source: https://pkg.go.dev/github.com/stretchr/testify/suite Defines a HandleStats method executed when a test suite finishes, providing execution statistics. Added in v1.6.0. ```go interface { HandleStats(suiteName string, stats *SuiteInformation) } ``` -------------------------------- ### Specify Mock Return Values Source: https://pkg.go.dev/github.com/stretchr/testify/mock Use `Return` to define the arguments that a mock should return when called. ```go func (c *Call) Return(returnArguments ...interface{}) *Call ``` ```go Mock.On("DoSomething").Return(errors.New("failed")) ``` -------------------------------- ### NoDirExists: Assert Directory Does Not Exist Source: https://pkg.go.dev/github.com/stretchr/testify/assert Use NoDirExists to check if a directory does not exist at the specified path. It specifically fails only if the path points to an existing directory. ```go func (a *Assertions) NoDirExists(path string, msgAndArgs ...interface{}) bool ``` -------------------------------- ### Assert HTTP Success with Formatting Source: https://pkg.go.dev/github.com/stretchr/testify/assert Asserts that a specified handler returns a success status code, with formatted error messages. Returns true if the assertion is successful, false otherwise. ```go func (a *Assertions) HTTPSuccessf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool a.HTTPSuccessf(myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") ``` -------------------------------- ### FileExistsf Source: https://pkg.go.dev/github.com/stretchr/testify/assert FileExistsf asserts that a file exists at the given path, with support for formatted error messages. ```APIDOC ## FileExistsf ### Description Asserts that a file exists at the given path. Formatted error message is supported. ### Signature func (a *Assertions) FileExistsf(path string, msg string, args ...interface{}) bool ``` -------------------------------- ### Same Source: https://pkg.go.dev/github.com/stretchr/testify/assert Asserts that two pointers reference the same object. ```APIDOC ## func Same ### Description 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. ### Signature ```go func Same(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool ``` ### Example ```go assert.Same(t, ptr1, ptr2) ``` ```