# Golang Stretchr Testify > Guía completa de stretchr/testify para testing en Golang: assert, require, mock y suite, con matchers, verificación de llamadas y patrones avanzados como Eventually y JSONEq. Fuente: https://skillsagentes.com/skills/samber/cc-skills-golang/golang-stretchr-testify Markdown: https://skillsagentes.com/skills/samber/cc-skills-golang/golang-stretchr-testify.md Repositorio: https://github.com/samber/cc-skills-golang Autor: samber Licencia: MIT Actualizado: el mes pasado Coste de contexto: 116 tok instalada, 1.8k tok al activarse, 5.7k tok con todos los archivos del bundle Bundle: 3 archivos, 22 KB Permisos que pide: read edit write glob grep bash(go:*) bash(golangci-lint:*) bash(git:*) agent webfetch mcp__context7__resolve-library-id mcp__context7__query-docs bash(gotests:*) askuserquestion bash(godig:*) bash(gopls:*) lsp mcp__gopls__* ## Instalación Un skill son archivos markdown: los mismos archivos valen para cualquier agente y lo único que cambia es el directorio de destino, es decir la bandera `--agent`. Añade `-g` para instalarlo en todos los proyectos de la máquina. ```bash # Claude Code npx -y skills add samber/cc-skills-golang --skill golang-stretchr-testify --agent claude-code # Cursor npx -y skills add samber/cc-skills-golang --skill golang-stretchr-testify --agent cursor # Codex npx -y skills add samber/cc-skills-golang --skill golang-stretchr-testify --agent codex # Gemini CLI npx -y skills add samber/cc-skills-golang --skill golang-stretchr-testify --agent gemini # Windsurf npx -y skills add samber/cc-skills-golang --skill golang-stretchr-testify --agent windsurf # Cline npx -y skills add samber/cc-skills-golang --skill golang-stretchr-testify --agent cline ``` ## Qué hace - Guía para escribir aserciones, mocks y suites con stretchr/testify en Go - Explica cuándo usar assert frente a require según el tipo de fallo esperado - Detalla matchers de mock (mock.Anything, MatchedBy) y modificadores de llamada (.Once, .Times, .Maybe) - Documenta el ciclo de vida de testify/suite (SetupSuite, SetupTest, TearDownTest) - Lista errores comunes: olvidar AssertExpectations, orden de argumentos invertido, comparar punteros ## Cuándo usarla - Al escribir tests con testify - Al crear mocks - Al configurar test suites - Al elegir entre assert y require, o cuando el código importa github.com/stretchr/testify ## Qué la activa - "Escribe tests con testify para este servicio" - "Crea un mock para esta interfaz usando testify/mock" - "Configura una test suite con SetupTest y TearDownTest" - "¿Cuándo debo usar require en vez de assert?" ## Antes de instalar - Requiere los binarios go y gotests, y que el proyecto importe github.com/stretchr/testify. ## Archivos - SKILL.md — 7 KB - evals/evals.json — 12 KB - references/mock.md — 3 KB ## SKILL.md Reproducido tal cual desde samber/cc-skills-golang bajo MIT. Esta sección es el documento original y está en inglés. **Persona:** You are a Go engineer who treats tests as executable specifications. You write tests to constrain behavior and make failures self-explanatory — not to hit coverage targets. **Modes:** - **Write mode** — adding new tests or mocks to a codebase. - **Review mode** — auditing existing test code for testify misuse. # stretchr/testify testify complements Go's `testing` package with readable assertions, mocks, and suites. It does not replace `testing` — always use `*testing.T` as the entry point. This skill is not exhaustive. Please refer to library documentation and code examples for more information. For Go package docs, symbols, versions, importers, and known vulnerabilities, → See `samber/cc-skills-golang@golang-pkg-go-dev` skill (`godig`) — prefer it over Context7 for Go package facts. To navigate this library's usage in your own code (definitions, call sites, diagnostics), → See `samber/cc-skills-golang@golang-gopls` skill (`gopls`). Context7 remains a fallback for docs not indexed on pkg.go.dev. ## assert vs require Both offer identical assertions. The difference is failure behavior: - **assert**: records failure, continues — see all failures at once - **require**: calls `t.FailNow()` — use for preconditions where continuing would panic or mislead Use `assert.New(t)` / `require.New(t)` for readability. Name them `is` and `must`: ```go func TestParseConfig(t *testing.T) { is := assert.New(t) must := require.New(t) cfg, err := ParseConfig("testdata/valid.yaml") must.NoError(err) // stop if parsing fails — cfg would be nil must.NotNil(cfg) is.Equal("production", cfg.Environment) is.Equal(8080, cfg.Port) is.True(cfg.TLS.Enabled) } ``` **Rule**: `require` for preconditions (setup, error checks), `assert` for verifications. Never mix randomly. ## Core Assertions ```go is := assert.New(t) // Equality is.Equal(expected, actual) // DeepEqual + exact type is.NotEqual(unexpected, actual) is.EqualValues(expected, actual) // converts to common type first is.EqualExportedValues(expected, actual) // Nil / Bool / Emptiness is.Nil(obj) is.NotNil(obj) is.True(cond) is.False(cond) is.Empty(collection) is.NotEmpty(collection) is.Len(collection, n) // Contains (strings, slices, map keys) is.Contains("hello world", "world") is.Contains([]int{1, 2, 3}, 2) is.Contains(map[string]int{"a": 1}, "a") // Comparison is.Greater(actual, threshold) is.Less(actual, ceiling) is.Positive(val) is.Negative(val) is.Zero(val) // Errors is.Error(err) is.NoError(err) is.ErrorIs(err, ErrNotFound) // walks error chain is.ErrorAs(err, &target) is.ErrorContains(err, "not found") // Type is.IsType(&User{}, obj) is.Implements((*io.Reader)(nil), obj) ``` **Argument order**: always `(expected, actual)` — swapping produces confusing diff output. ## Advanced Assertions ```go is.ElementsMatch([]string{"b", "a", "c"}, result) // unordered comparison is.InDelta(3.14, computedPi, 0.01) // float tolerance is.JSONEq(`{"name":"alice"}`, `{"name": "alice"}`) // ignores whitespace/key order is.WithinDuration(expected, actual, 5*time.Second) is.Regexp(`^user-[a-f0-9]+$`, userID) // Async polling is.Eventually(func() bool { status, _ := client.GetJobStatus(jobID) return status == "completed" }, 5*time.Second, 100*time.Millisecond) // Async polling with rich assertions is.EventuallyWithT(func(c *assert.CollectT) { resp, err := client.GetOrder(orderID) assert.NoError(c, err) assert.Equal(c, "shipped", resp.Status) }, 10*time.Second, 500*time.Millisecond) ``` ## testify/mock Mock interfaces to isolate the unit under test. Embed `mock.Mock`, implement methods with `m.Called()`, always verify with `AssertExpectations(t)`. Key matchers: `mock.Anything`, `mock.AnythingOfType("T")`, `mock.MatchedBy(func)`. Call modifiers: `.Once()`, `.Times(n)`, `.Maybe()`, `.Run(func)`. For defining mocks, argument matchers, call modifiers, return sequences, and verification, see [Mock reference](./references/mock.md). ## testify/suite Suites group related tests with shared setup/teardown. ### Lifecycle ``` SetupSuite() → once before all tests SetupTest() → before each test TestXxx() TearDownTest() → after each test TearDownSuite() → once after all tests ``` ### Example ```go type TokenServiceSuite struct { suite.Suite store *MockTokenStore service *TokenService } func (s *TokenServiceSuite) SetupTest() { s.store = new(MockTokenStore) s.service = NewTokenService(s.store) } func (s *TokenServiceSuite) TestGenerate_ReturnsValidToken() { s.store.On("Save", mock.Anything, mock.Anything).Return(nil) token, err := s.service.Generate("user-42") s.NoError(err) s.NotEmpty(token) s.store.AssertExpectations(s.T()) } // Required launcher func TestTokenServiceSuite(t *testing.T) { suite.Run(t, new(TokenServiceSuite)) } ``` Suite methods like `s.Equal()` behave like `assert`. For require: `s.Require().NotNil(obj)`. ## Common Mistakes - **Forgetting `AssertExpectations(t)`** — mock expectations silently pass without verification - **`is.Equal(ErrNotFound, err)`** — fails on wrapped errors. Use `is.ErrorIs` to walk the chain - **Swapped argument order** — testify assumes `(expected, actual)`. Swapping produces backwards diffs - **`assert` for guards** — test continues after failure and panics on nil dereference. Use `require` - **Missing `suite.Run()`** — without the launcher function, zero tests execute silently - **Comparing pointers** — `is.Equal(ptr1, ptr2)` compares addresses. Dereference or use `EqualExportedValues` ## Linters Use `testifylint` to catch wrong argument order, assert/require misuse, and more. See `samber/cc-skills-golang@golang-lint` skill. ## Cross-References - → See `samber/cc-skills-golang@golang-testing` skill for general test patterns, table-driven tests, and CI - → See `samber/cc-skills-golang@golang-lint` skill for testifylint configuration ## Dónde encaja - Categoría: [Testing y QA](https://skillsagentes.com/categorias/testing-qa.md) — Flujos de testing unitario, de integración y end-to-end. - Creador: [samber](https://skillsagentes.com/creators/samber.md) — 0 skills en el directorio - [Todas las skills](https://skillsagentes.com/skills.md) - [Ranking de instalaciones](https://skillsagentes.com/ranking.md) ## Otras skills del mismo repositorio - [Golang Lint](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-lint.md): Buenas prácticas de linting y configuración de golangci-lint para proyectos Golang: ejecutar linters, configurar .golangci.yml, suprimir avisos con nolint, interpretar salidas y elegir linters. - [Golang How To](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-how-to.md): Orquestador de skills de Golang, siempre activo en cualquier tarea de código, revisión, debug o setup: carga las skills más relevantes de samber/cc-skills-golang, a menudo varias a la vez. - [Golang Benchmark](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-benchmark.md): Benchmarking, profiling y medición de rendimiento en Golang: escribir y comparar benchmarks, perfilar con pprof, analizar con benchstat y detectar regresiones en CI. - [Golang Testing](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-testing.md): Tests de Golang listos para producción: table-driven, suites y mocks con testify, tests paralelos, fuzzing, fixtures, detección de fugas de goroutines con goleak, snapshot testing, cobertura, tests de integración. - [Golang Performance](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-performance.md): Patrones y metodología de optimización de rendimiento en Golang: si hay cuello de botella X, aplica el patrón Y, una vez que profiling o benchmarks ya lo identificaron. ## Skills relacionadas - [Golang Safety](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-safety.md): Codificación defensiva en Golang para evitar panics, corrupción silenciosa de datos y bugs sutiles en tiempo de ejecución. - [Golang Testing](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-testing.md): Tests de Golang listos para producción: table-driven, suites y mocks con testify, tests paralelos, fuzzing, fixtures, detección de fugas de goroutines con goleak, snapshot testing, cobertura, tests de integración. - [Golang Troubleshooting](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-troubleshooting.md): Depura programas Go de forma sistemática hasta encontrar y corregir la causa raíz: metodología de debugging, errores comunes de Go, pprof, Delve, detección de races y depuración en producción. - [Golang Benchmark](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-benchmark.md): Benchmarking, profiling y medición de rendimiento en Golang: escribir y comparar benchmarks, perfilar con pprof, analizar con benchstat y detectar regresiones en CI. - [Golang Graphql](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-graphql.md): Implementa APIs GraphQL en Golang con gqlgen o graphql-go: diseño de schemas, resolvers, suscripciones e integración con servicios HTTP en Go. --- Skills Agentes · [Índice de páginas en markdown](https://skillsagentes.com/sitemap.md) · [Inicio](https://skillsagentes.com/index.md)