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

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 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.")
}

オリジンシーダー

匿名