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.
Instalación lista para agent
Este activo puede instalarse después de elegir el runtime, revisar el plan y ejecutar el comando correspondiente.
npx -y tokrepo@latest install 1056f32f-373d-11f1-9bc6-00163e2b0d79 --target codexEjecutar después de confirmar el plan con 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.
Preguntas frecuentes
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.
Referencias (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
Relacionados en TokRepo
Discusión
Activos relacionados
Mockery — Go Interface Mock Code Generator
A code generation tool that creates mock implementations of Go interfaces for use in unit tests. Integrates with testify/mock and supports automatic regeneration via go generate.
Ant Design — Enterprise-Class React UI Library
Ant Design is an enterprise-class UI design language and React component library created by Alibaba. 60+ production-ready components with comprehensive patterns, internationalization for 30+ languages, and a rich theme system. The go-to choice for admin dashboards.
Semantic UI — Human-Friendly UI Component Framework
Semantic UI is a front-end component framework that uses human-friendly HTML class names to create responsive, themeable layouts. It provides over 50 UI components designed around natural language principles.
Kepler.gl — Open Source Geospatial Data Visualization
A powerful open-source tool for large-scale geospatial data visualization built on deck.gl and Mapbox GL.