Install the module:
go get github.com/stretchr/testify@v1.11.1The pinned commit this reference was generated from is
87a7b9d57689f6579db2da795ab8deeab29cb724.
assert and require
assert reports a failure and lets the test continue; require reports a failure and stops the
test immediately. Use require when a later assertion would panic on a nil result.
package mypkg_test
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestAdd(t *testing.T) {
got := Add(2, 3)
require.Equal(t, 5, got, "Add must add its arguments")
assert.Equal(t, 5, got)
assert.NoError(t, err)
}Every assert function has a …f twin that takes a format string — assert.Equalf(t, 5, got, "Add(%d,%d) returned %d", 2, 3, got) — and both families are listed in the API Reference.
mock
A mock embeds mock.Mock and implements the interface by hand, so the expectation and the
return value are declared in the test.
package mypkg_test
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
type mockStore struct{ mock.Mock }
func (m *mockStore) Get(key string) (int, error) {
args := m.Called(key)
return args.Int(0), args.Error(1)
}
func TestGet(t *testing.T) {
store := new(mockStore)
store.On("Get", "abc").Return(42, nil)
value, err := store.Get("abc")
require.NoError(t, err)
assert.Equal(t, 42, value)
store.AssertExpectations(t)
}suite
A suite groups related tests and gives you per-test setup and teardown.
package mypkg_test
import (
"testing"
"github.com/stretchr/testify/suite"
)
type UserSuite struct {
suite.Suite
}
func (s *UserSuite) SetupTest() {
s.T().Log("fresh state for each test")
}
func (s *UserSuite) TestGet() {
s.Equal(42, 42)
}
func TestUserSuite(t *testing.T) {
suite.Run(t, new(UserSuite))
}http
http contains the httptest helpers: a TestResponseWriter that records the response and a
TestRoundTripper that replays canned responses.
package mypkg_test
import (
"net/http"
"testing"
"github.com/stretchr/testify/http"
"github.com/stretchr/testify/require"
)
func TestHandler(t *testing.T) {
rec := new(http.TestResponseWriter)
handler(rec, new(http.Request))
require.Equal(t, http.StatusOK, rec.Result().StatusCode)
}