golang-stretchr-testify

tarafından samber

Golang testlerinde stretchr/testify kullanımına dair kapsamlı rehber. assert, require, mock ve suite paketlerini derinlemesine ele alır. Testify ile test yazarken, mock oluştururken, test suiteleri kurarken veya assert ile require arasında seçim yaparken kullanılır. Testify assertion'ları, mock beklentileri, argüman eşleştiricileri, çağrı doğrulama, suite yaşam döngüsü ve Eventually, JSONEq, özel eşleştiriciler gibi ileri düzey desenleri kapsar. Kod tabanı github.com/stretchr/testify import ettiğinde uygulanır.

npx skills add https://github.com/samber/cc-skills-golang --skill golang-stretchr-testify

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. Context7 can help as a discoverability platform.

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:

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

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

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.

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

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 pointersis.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

samber tarafından daha fazla skill

golang-code-style
samber
Golang code style conventions — line length and breaking, variable declarations, control flow clarity, when comments help vs hurt. Use when writing or reviewing Go code, asking about style or clarity, or establishing project coding standards. Not for naming conventions (→ See `samber/cc-skills-golang@golang-naming` skill), linter configuration (→ See `samber/cc-skills-golang@golang-lint` skill), or doc comments (→ See `samber/cc-skills-golang@golang-documentation` skill).
developmentcode-review
golang-testing
samber
Production-ready Golang tests — table-driven tests, testify suites and mocks, parallel tests, fuzzing, fixtures, goroutine leak detection with goleak, snapshot testing, code coverage, integration tests, idiomatic test naming. Use when writing or reviewing Go tests, choosing a testing approach, setting up Go test CI, or debugging flaky/slow tests. For testify-specific APIs see `samber/cc-skills-golang@golang-stretchr-testify`; for measurement methodology see...
developmenttestingcode-review
golang-design-patterns
samber
Idiomatic Golang tasarım desenleri — fonksiyonel seçenekler, yapıcılar, hata akışı ve basamaklama, kaynak yönetimi ve yaşam döngüsü, zarif kapanış, dayanıklılık, mimari, bağımlılık enjeksiyonu, veri işleme, akış ve daha fazlası. Mimari desenler arasında açıkça seçim yaparken, fonksiyonel seçenekleri uygularken, yapıcı API'leri tasarlarken, zarif kapanış ayarlarken, dayanıklılık desenlerini uygularken veya belirli bir soruna hangi idiomatic Go deseninin uyduğunu sorarken uygulayın.
developmentdesigncode-review
golang-error-handling
samber
Idiomatic Golang error handling — creation, wrapping with %w, errors.Is/As, errors.Join, custom error types, sentinel errors, panic/recover, the single handling rule, structured logging with slog, HTTP request logging middleware, and samber/oops for production errors. Built to make logs usable at scale with log aggregation 3rd-party tools. Apply when creating, wrapping, inspecting, or logging errors in Go code. For samber/oops specifics → See `samber/cc-skills-golang@golang-samber-oops`...
developmentcode-review
golang-performance
samber
Golang performans optimizasyonu kalıpları ve metodolojisi - eğer X darboğazı varsa, Y uygulanır. Tahsis azaltma, CPU verimliliği, bellek düzeni, GC ayarlama, havuzlama, önbellekleme ve sıcak yol optimizasyonunu kapsar. Profilleme veya kıyaslamalar bir darboğaz tespit ettiğinde ve bunu düzeltmek için doğru optimizasyon kalıbına ihtiyaç duyduğunuzda kullanın. Ayrıca, hızlı performans kazanımlarını belirlemeye yardımcı olabilecek iyileştirmeler veya kıyaslamalar önermek için performans kod incelemesi yaparken de kullanın. Ölçüm metodolojisi için değildir (→...
developmentcode-review
golang-security
samber
Golang için güvenlik en iyi uygulamaları ve zafiyet önleme. Enjeksiyon (SQL, komut, XSS), kriptografi, dosya sistemi güvenliği, ağ güvenliği, çerezler, sır yönetimi, bellek güvenliği ve günlükleme konularını kapsar. Go kodunu güvenlik açısından yazarken, incelerken veya denetlerken ya da kripto, G/Ç, sır yönetimi, kullanıcı girişi işleme veya kimlik doğrulama içeren riskli kodlar üzerinde çalışırken uygulayın. Güvenlik araçlarının yapılandırmasını içerir.
securitycode-reviewdevelopment
golang-database
samber
Go veritabanı erişimi için kapsamlı rehber — parametrik sorgular, struct tarama, NULL yapılabilir sütunlar, işlemler, izolasyon seviyeleri, SELECT FOR UPDATE, bağlantı havuzu, toplu işleme, bağlam yayılımı ve geçiş araçları. PostgreSQL, MariaDB, MySQL veya SQLite ile etkileşim kuran Golang kodu yazarken, gözden geçirirken veya hata ayıklarken; veritabanı testi için; veya database/sql, sqlx veya pgx ile ilgili sorular için kullanın. Veritabanı şemaları veya geçiş SQL’i oluşturmaz.
developmentdatabase
golang-lint
samber
Golang projeleri için linting en iyi uygulamaları ve golangci-lint yapılandırması — linterları çalıştırma, .golangci.yml yapılandırma, nolint yönergeleriyle uyarıları bastırma, lint çıktısını yorumlama ve linter seçimi. golangci-lint yapılandırırken, lint uyarıları veya nolint bastırmaları hakkında soru sorarken, kod kalitesi araçları kurarken veya linter seçerken kullanın. Ayrıca kullanıcı golangci-lint, go vet, staticcheck veya revive'den bahsettiğinde de kullanın.
developmentcode-reviewtesting