CodeSampleX

샘플

github.com/stretchr/testify v1.11.1: Verify testify mock method call expectations, argument matchers, and return values

검증된 샘플 — golang github.com/stretchr/testify v1.11.1: Verify testify mock method call expectations, argument matchers, and return values. go 1.26 · linux…

sha256:1354203e1c5d9064c73519c4f1bf57081ea1dae1494ac6d0643d617b32dc10e0

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 go

검증 실행 환경

환경 컨트랙트 단계 실행일
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-23

케이스

HOW
목표
Verify testify mock method call expectations, argument matchers, and return values
패키지
생성일
2026-08-23T06:08:36Z

컨트랙트

  1. mock.Mock.On registers expected method calls and returns configured values upon mock.Mock.Called
  2. mock.MatchedBy matches method arguments using custom predicate functions
  3. mock.Anything and mock.AnythingOfType match arbitrary arguments and type-specific arguments
  4. mock.Mock.AssertExpectations verifies that all expected calls were executed
  5. mock.Mock.AssertCalled and mock.Mock.AssertNotCalled verify whether specific method invocations occurred

파일

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.go
  • spec.json
  • test/contract.go

소스 아티팩트 내려받기 (tar.gz)

소스

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: Verify testify mock method call expectations, argument matchers, and return values
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/stretchr/testify@v1.11.1

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:8df1ca1b03a969101ac8d2ddbbed481fe9752e91b52e7dadef4634bd2981dfe7","contract":["mock.Mock.On registers expected method calls and returns configured values upon mock.Mock.Called","mock.MatchedBy matches method arguments using custom predicate functions","mock.Anything and mock.AnythingOfType match arbitrary arguments and type-specific arguments","mock.Mock.AssertExpectations verifies that all expected calls were executed","mock.Mock.AssertCalled and mock.Mock.AssertNotCalled verify whether specific method invocations occurred"],"goal":"Verify testify mock method call expectations, argument matchers, and return values","kind":"HOW","packages":["pkg:golang/github.com/stretchr/testify@v1.11.1"],"schemaVersion":1},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/stretchr/testify@v1.11.1"],"schemaVersion":1,"subject":"pkg:golang/github.com/stretchr/testify@v1.11.1","verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.26.6

require github.com/stretchr/testify v1.11.1

require (
	github.com/davecgh/go-spew v1.1.1 // indirect
	github.com/pmezard/go-difflib v1.0.0 // indirect
	github.com/stretchr/objx v0.5.2 // indirect
	gopkg.in/yaml.v3 v3.0.1 // indirect
)
go.sum
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
main.go
package main

import (
	"errors"
	"fmt"
	"log"

	"github.com/stretchr/testify/mock"
)

// DataStore represents a service interface to mock.
type DataStore interface {
	GetUser(id int) (string, error)
	SaveUser(id int, name string) bool
	CalculateScore(multiplier int, tag string) int
}

// MockDataStore is a mock implementation of DataStore.
type MockDataStore struct {
	mock.Mock
}

func (m *MockDataStore) GetUser(id int) (string, error) {
	args := m.Called(id)
	return args.String(0), args.Error(1)
}

func (m *MockDataStore) SaveUser(id int, name string) bool {
	args := m.Called(id, name)
	return args.Bool(0)
}

func (m *MockDataStore) CalculateScore(multiplier int, tag string) int {
	args := m.Called(multiplier, tag)
	return args.Int(0)
}

func main() {
	mockStore := new(MockDataStore)

	// 1. Setup exact argument match expectation with Return
	mockStore.On("GetUser", 42).Return("Alice", nil)
	mockStore.On("GetUser", 99).Return("", errors.New("user not found"))

	// 2. Setup mock.MatchedBy predicate matcher
	mockStore.On("SaveUser", mock.MatchedBy(func(id int) bool {
		return id > 0 && id < 1000
	}), mock.AnythingOfType("string")).Return(true)

	// 3. Setup mock.Anything matcher
	mockStore.On("CalculateScore", 10, mock.Anything).Return(100)

	// Execute calls
	user, err := mockStore.GetUser(42)
	if err != nil || user != "Alice" {
		log.Fatalf("unexpected GetUser(42) result: user=%q, err=%v", user, err)
	}
	fmt.Printf("GetUser(42) = %s\n", user)

	_, notFoundErr := mockStore.GetUser(99)
	if notFoundErr == nil {
		log.Fatalf("expected error for GetUser(99), got nil")
	}
	fmt.Printf("GetUser(99) returned expected error: %v\n", notFoundErr)

	saved := mockStore.SaveUser(100, "Bob")
	if !saved {
		log.Fatalf("expected SaveUser to return true")
	}
	fmt.Printf("SaveUser(100, \"Bob\") = %v\n", saved)

	score := mockStore.CalculateScore(10, "admin-priority")
	if score != 100 {
		log.Fatalf("expected score 100, got %d", score)
	}
	fmt.Printf("CalculateScore(10, \"admin-priority\") = %d\n", score)

	fmt.Println("Testify mock demonstration completed successfully.")
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Verify testify mock method call expectations, argument matchers, and return values",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/stretchr/testify@v1.11.1"
  ]
}
test/contract.go
package main

import (
	"errors"
	"fmt"
	"os"

	"github.com/stretchr/testify/mock"
)

type dummyTestingT struct {
	errors []string
	failed bool
}

func (t *dummyTestingT) Logf(format string, args ...interface{}) {}
func (t *dummyTestingT) Errorf(format string, args ...interface{}) {
	t.errors = append(t.errors, fmt.Sprintf(format, args...))
	t.failed = true
}
func (t *dummyTestingT) FailNow() {
	t.failed = true
}

type ServiceMock struct {
	mock.Mock
}

func (m *ServiceMock) Fetch(id int) (string, error) {
	args := m.Called(id)
	return args.String(0), args.Error(1)
}

func (m *ServiceMock) Store(key string, val int) bool {
	args := m.Called(key, val)
	return args.Bool(0)
}

func (m *ServiceMock) Process(category string, count int) int {
	args := m.Called(category, count)
	return args.Int(0)
}

func main() {
	// Assertion 1: mock.Mock.On sets up method call expectations and returns configured Return values upon mock.Mock.Called
	{
		m := new(ServiceMock)
		expectedErr := errors.New("not found")
		m.On("Fetch", 1).Return("data-1", nil)
		m.On("Fetch", 2).Return("", expectedErr)

		gotStr1, gotErr1 := m.Fetch(1)
		if gotStr1 != "data-1" || gotErr1 != nil {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: Fetch(1) = (%q, %v), want (\"data-1\", nil)\n", gotStr1, gotErr1)
			os.Exit(1)
		}

		gotStr2, gotErr2 := m.Fetch(2)
		if gotStr2 != "" || !errors.Is(gotErr2, expectedErr) {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: Fetch(2) = (%q, %v), want (\"\", %v)\n", gotStr2, gotErr2, expectedErr)
			os.Exit(1)
		}
	}

	// Assertion 2: mock.MatchedBy matches method call arguments using custom predicate functions
	{
		m := new(ServiceMock)
		isPositive := func(val int) bool { return val > 0 }
		isNonEmpty := func(key string) bool { return len(key) > 0 }

		m.On("Store", mock.MatchedBy(isNonEmpty), mock.MatchedBy(isPositive)).Return(true)

		if ok := m.Store("session", 42); !ok {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: Store with matched arguments returned false, want true\n")
			os.Exit(1)
		}
	}

	// Assertion 3: mock.Anything and mock.AnythingOfType match any argument or argument of a specific type
	{
		m := new(ServiceMock)
		m.On("Process", mock.AnythingOfType("string"), mock.Anything).Return(999)

		result := m.Process("test-category", 12345)
		if result != 999 {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: Process returned %d, want 999\n", result)
			os.Exit(1)
		}
	}

	// Assertion 4: mock.Mock.AssertExpectations verifies that all expected method calls were executed
	{
		// Subtest A: satisfied expectations
		tSatisfied := &dummyTestingT{}
		mSatisfied := new(ServiceMock)
		mSatisfied.On("Fetch", 10).Return("ten", nil).Once()
		mSatisfied.Fetch(10)

		if !mSatisfied.AssertExpectations(tSatisfied) || tSatisfied.failed {
			fmt.Fprintf(os.Stderr, "assertion 4 failed: AssertExpectations should return true for satisfied mock\n")
			os.Exit(1)
		}

		// Subtest B: unsatisfied expectations
		tUnsatisfied := &dummyTestingT{}
		mUnsatisfied := new(ServiceMock)
		mUnsatisfied.On("Fetch", 20).Return("twenty", nil).Once()
		// Do not call Fetch(20)

		if mUnsatisfied.AssertExpectations(tUnsatisfied) || !tUnsatisfied.failed {
			fmt.Fprintf(os.Stderr, "assertion 4 failed: AssertExpectations should report failure for unsatisfied mock\n")
			os.Exit(1)
		}
	}

	// Assertion 5: mock.Mock.AssertCalled and mock.Mock.AssertNotCalled verify whether specific method invocations occurred
	{
		tCall := &dummyTestingT{}
		m := new(ServiceMock)
		m.On("Store", "config", 1).Return(true)
		m.Store("config", 1)

		if !m.AssertCalled(tCall, "Store", "config", 1) || tCall.failed {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: AssertCalled should return true for called method\n")
			os.Exit(1)
		}

		if !m.AssertNotCalled(tCall, "Fetch", 999) || tCall.failed {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: AssertNotCalled should return true for uncalled method\n")
			os.Exit(1)
		}
	}

	fmt.Println("All contract assertions passed.")
}

오리진 시더

익명