The testify/require
package is a popular assertion library for Go tests, which is part of the broader testify
package. It provides a set of functions to make writing assertions easier and more readable. The require
package is similar to the assert
package in testify
, but it stops test execution immediately if an assertion fails.
To install the testify
package. Run the following command:
go get github.com/stretchr/testify
Example code
package example
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestSomething(t *testing.T) {
// Example assertion: checking equality
expected := 42
actual := 42
require.Equal(t, expected, actual, "The two values should be equal")
// Example assertion: checking inequality
require.NotEqual(t, 123, 456, "These two values should not be equal")
// Example assertion: checking a condition
require.True(t, 10 > 5, "10 should be greater than 5")
// Example assertion: checking nil
var somePointer *int
require.Nil(t, somePointer, "Pointer should be nil")
// Example assertion: checking not nil
somePointer = new(int)
require.NotNil(t, somePointer, "Pointer should not be nil")
// Example assertion: checking error
err := someFunctionThatMightReturnError()
require.NoError(t, err, "There should be no error")
}
// Mock function for demonstration
func someFunctionThatMightReturnError() error {
return nil
}
Here is how to use the require
package to make assertions
require.[function](t, expected, actual, "optional comment")
Require equal
require.Equal(t, expected, actual)
Require not equal
require.NotEqual(t, expected, actual)
Check if a key is in a map
require.Contains(t, sampleMap, key)
Check if a key is not in a map
require.NotContains(t, sampleMap, key)
Check if a value is in a slice
require.Contains(t, sampleSlice, value)
Check that a slice, map or string is not empty
require.NotEmpty(t, object)