Testify — Go Testing Toolkit with Assertions and Mocks
Testify is the most popular Go testing toolkit. It provides expressive assertions (assert/require), powerful mocking, and test suites with setup/teardown — making Go tests more readable and maintainable than the standard library alone.
Agent 可直接安装
这个资产可安装;Agent 先选择当前运行时、检查安装计划,再运行匹配命令。
npx -y tokrepo@latest install 1056f32f-373d-11f1-9bc6-00163e2b0d79 --target codex先 dry-run 确认安装计划,再运行此命令。
What it is
Testify is the most widely used Go testing toolkit. It extends Go's standard testing package with three components: assert (soft assertions that log failures and continue), require (hard assertions that stop the test), and mock (interface mocking with expectations and verifications).
It targets Go developers who find the standard if got != want { t.Errorf(...) } pattern too verbose. Testify makes tests more readable and reduces boilerplate without replacing Go's test runner.
How it saves time or tokens
A typical Go test without Testify requires 3-4 lines per assertion (check, format error message, call t.Errorf). Testify reduces this to one line: assert.Equal(t, expected, actual). For a test file with 50 assertions, this saves 100-150 lines of boilerplate.
The mock package generates mock implementations from interfaces, eliminating the need to write manual mock structs.
How to use
- Install Testify:
go get github.com/stretchr/testify
- Write assertions:
package mypackage
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestUser(t *testing.T) {
user, err := GetUser(1)
require.NoError(t, err) // stops test if err != nil
assert.Equal(t, "Alice", user.Name)
assert.NotEmpty(t, user.Email)
assert.Contains(t, user.Roles, "admin")
}
- Use mocks for interface dependencies:
import "github.com/stretchr/testify/mock"
type MockDB struct { mock.Mock }
func (m *MockDB) GetUser(id int) (*User, error) {
args := m.Called(id)
return args.Get(0).(*User), args.Error(1)
}
Example
// Test suite with setup/teardown
package mypackage
import (
"testing"
"github.com/stretchr/testify/suite"
)
type UserSuite struct {
suite.Suite
db *TestDB
}
func (s *UserSuite) SetupTest() {
s.db = NewTestDB()
s.db.Seed()
}
func (s *UserSuite) TearDownTest() {
s.db.Clean()
}
func (s *UserSuite) TestCreateUser() {
user, err := s.db.CreateUser("Charlie")
s.Require().NoError(err)
s.Equal("Charlie", user.Name)
}
func TestUserSuite(t *testing.T) {
suite.Run(t, new(UserSuite))
}
Related on TokRepo
- AI Tools for Testing -- Automated testing tools and frameworks
- AI Tools for Coding -- Developer tools and coding assistants
Common pitfalls
- Use
requirefor preconditions (like checking errors) andassertfor value checks. Usingassertfor error checks means the test continues with a nil pointer. - Testify mock expectations must be verified with
mock.AssertExpectations(t)at the end of the test. Forgetting this means unmet expectations pass silently. - Do not import both
assertandrequireunder the same alias. Use their package names as-is to keep test code clear.
常见问题
No. Testify extends the standard testing package. You still run tests with `go test`. Testify provides better assertions and mocks but uses Go's built-in test runner.
assert logs a failure and continues the test. require logs a failure and stops the test immediately via t.FailNow(). Use require for preconditions where continuing would cause panics (like nil error checks).
Yes. Use the mockery tool (`go install github.com/vektra/mockery/v2@latest`) to generate Testify mock implementations from Go interfaces automatically.
Testify is the most popular third-party testing library in the Go ecosystem. Many Go projects use it, though some teams prefer the standard library approach or alternative libraries like goconvey.
Testify works well with Go's table-driven test pattern. Use assert or require inside the loop body of a table-driven test with t.Run() subtests for clear output.
引用来源 (3)
- Testify GitHub Repository— Testify provides assertions, mocks, and test suites for Go
- Testify Documentation— assert for soft failures, require for hard failures
- mockery GitHub Repository— mockery generates Testify mocks from Go interfaces
讨论
相关资产
Ginkgo — BDD Testing Framework for Go
An expressive BDD-style testing framework for Go with support for spec nesting, lifecycle hooks, parallel execution, and structured test output. Pairs with the Gomega matcher library.
k6 — Modern Load Testing Tool Using Go and JavaScript
k6 is a modern load testing tool built by Grafana Labs. Write test scripts in JavaScript, run them in a high-performance Go runtime. Developer-centric with CLI-first workflow, CI/CD integration, and Grafana Cloud for result analysis.
GORM — The Fantastic ORM Library for Go
GORM is the most popular ORM for Go. It provides a developer-friendly API for database operations — auto-migration, associations, hooks, transactions, and query building — with support for PostgreSQL, MySQL, SQLite, and SQL Server.
GoConvey — Go Testing with Browser UI
A BDD-style testing framework for Go that includes a live-reloading browser interface. Write expressive specs with nested Convey blocks and watch results update in real time.