CodeSampleX

Exemple

go.uber.org/mock v0.5.0: mock interface with gomock Controller and verify call expectations

Échantillon vérifié pour golang go.uber.org/mock v0.5.0: mock interface with gomock Controller and verify call expectations. Le contrat s'est exécuté sur go…

sha256:cdf730346cb95267625cb2ec95b3b3b95dd6a51a6d790b065c194be08d8b520f

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
2
Clés de signature qui l’ont compilé
2
Environnement déclaré go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
go 1.26 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-23
go 1.26 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a…
2026-09-07

Cas

HOW
Objectif
mock interface with gomock Controller and verify call expectations
Paquets
Symboles
  • gomock.Controller.Finish
  • gomock.InOrder
  • gomock.NewController
Environnement
go 1.26
Créé
2026-08-23T16:40:32Z

Contrat

  1. NewController initializes an active Controller for managing mock lifecycles
  2. EXPECT records method call expectations with custom return values and matchers
  3. InOrder enforces strict sequential ordering across mock method calls
  4. Finish validates that all recorded mock expectations were fully satisfied
  5. Mock calls support error returns and call count constraints

Fichiers

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • mock.go
  • spec.json
  • test/contract_test.go

Télécharger l’artefact source (tar.gz)

Code source

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: mock interface with gomock Controller and verify call expectations
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/go.uber.org/mock@v0.5.0
Demonstrate these symbols/APIs:
  - gomock.Controller.Finish
  - gomock.InOrder
  - gomock.NewController
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:430ba53a3381dbfece3e82127d850df21ab32f6cbca20aeb9038c5fdbaa7deb4","contract":["NewController initializes an active Controller for managing mock lifecycles","EXPECT records method call expectations with custom return values and matchers","InOrder enforces strict sequential ordering across mock method calls","Finish validates that all recorded mock expectations were fully satisfied","Mock calls support error returns and call count constraints"],"goal":"mock interface with gomock Controller and verify call expectations","kind":"HOW","packages":["pkg:golang/go.uber.org/mock@v0.5.0"],"schemaVersion":1,"symbols":["gomock.Controller.Finish","gomock.InOrder","gomock.NewController"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","moduleSystem":"go.mod","os":"linux","osVersionBucket":"24","packageManager":"go","runtime":"go","runtimeVersion":"1.26","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/go.uber.org/mock@v0.5.0"],"schemaVersion":1,"subject":"pkg:golang/go.uber.org/mock@v0.5.0","symbols":["gomock.Controller.Finish","gomock.InOrder","gomock.NewController"],"verifierAdapter":"golang@1"}
go.mod
module example.com/gomock-controller

go 1.24.0

require go.uber.org/mock v0.5.0
go.sum
go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM=
mock.go
package sample

import (
	"errors"
	"fmt"
	"reflect"

	"go.uber.org/mock/gomock"
)

// UserRepository defines operations for managing user data.
type UserRepository interface {
	FindUser(id string) (string, error)
	SaveUser(id, name string) error
}

// MockUserRepository is a mock implementation of UserRepository for testing.
type MockUserRepository struct {
	ctrl     *gomock.Controller
	recorder *MockUserRepositoryMockRecorder
}

// MockUserRepositoryMockRecorder is the mock recorder for MockUserRepository.
type MockUserRepositoryMockRecorder struct {
	mock *MockUserRepository
}

// NewMockUserRepository creates a new mock instance.
func NewMockUserRepository(ctrl *gomock.Controller) *MockUserRepository {
	mock := &MockUserRepository{ctrl: ctrl}
	mock.recorder = &MockUserRepositoryMockRecorder{mock: mock}
	return mock
}

// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockUserRepository) EXPECT() *MockUserRepositoryMockRecorder {
	return m.recorder
}

// FindUser mocks base method.
func (m *MockUserRepository) FindUser(id string) (string, error) {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "FindUser", id)
	ret0, _ := ret[0].(string)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}

// FindUser indicates an expected call of FindUser.
func (mr *MockUserRepositoryMockRecorder) FindUser(id any) *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindUser", reflect.TypeOf((*MockUserRepository)(nil).FindUser), id)
}

// SaveUser mocks base method.
func (m *MockUserRepository) SaveUser(id, name string) error {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "SaveUser", id, name)
	ret0, _ := ret[0].(error)
	return ret0
}

// SaveUser indicates an expected call of SaveUser.
func (mr *MockUserRepositoryMockRecorder) SaveUser(id, name any) *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaveUser", reflect.TypeOf((*MockUserRepository)(nil).SaveUser), id, name)
}

// UserService provides business logic using UserRepository.
type UserService struct {
	repo UserRepository
}

// NewUserService creates a new UserService.
func NewUserService(repo UserRepository) *UserService {
	return &UserService{repo: repo}
}

// Register registers a new user with validation.
func (s *UserService) Register(id, name string) error {
	if id == "" || name == "" {
		return errors.New("invalid user credentials")
	}
	return s.repo.SaveUser(id, name)
}

// GetGreeting returns a greeting for the specified user.
func (s *UserService) GetGreeting(id string) (string, error) {
	name, err := s.repo.FindUser(id)
	if err != nil {
		return "", fmt.Errorf("failed to find user: %w", err)
	}
	return fmt.Sprintf("Hello, %s!", name), nil
}
spec.json
{
  "schemaVersion": 1,
  "goal": "mock interface with gomock Controller and verify call expectations",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.uber.org/mock@v0.5.0"
  ],
  "symbols": [
    "gomock.Controller.Finish",
    "gomock.InOrder",
    "gomock.NewController"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract_test.go
package test

import (
	"errors"
	"testing"

	sample "example.com/gomock-controller"
	"go.uber.org/mock/gomock"
)

func TestGomockControllerContract(t *testing.T) {
	// 1. NewController initializes an active Controller for managing mock lifecycles
	ctrl := gomock.NewController(t)
	if ctrl == nil {
		t.Fatal("expected non-nil Controller from gomock.NewController")
	}

	mockRepo := sample.NewMockUserRepository(ctrl)
	service := sample.NewUserService(mockRepo)

	// 2. EXPECT records method call expectations with custom return values and matchers
	mockRepo.EXPECT().
		SaveUser(gomock.Eq("u-101"), gomock.Eq("Alice")).
		Return(nil).
		Times(1)

	if err := service.Register("u-101", "Alice"); err != nil {
		t.Fatalf("unexpected error registering user: %v", err)
	}

	// 3. InOrder enforces strict sequential ordering across mock method calls
	callFirst := mockRepo.EXPECT().SaveUser("u-202", "Bob").Return(nil)
	callSecond := mockRepo.EXPECT().FindUser("u-202").Return("Bob", nil)
	gomock.InOrder(callFirst, callSecond)

	if err := mockRepo.SaveUser("u-202", "Bob"); err != nil {
		t.Fatalf("unexpected save error in order sequence: %v", err)
	}
	greeting, err := service.GetGreeting("u-202")
	if err != nil {
		t.Fatalf("unexpected get error in order sequence: %v", err)
	}
	if greeting != "Hello, Bob!" {
		t.Fatalf("expected 'Hello, Bob!', got %q", greeting)
	}

	// 4. Finish validates that all recorded mock expectations were fully satisfied
	ctrl.Finish()
}

func TestGomockErrorsAndConstraintsContract(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	mockRepo := sample.NewMockUserRepository(ctrl)
	service := sample.NewUserService(mockRepo)

	// 5. Mock calls support error returns and call count constraints
	expectedErr := errors.New("user not found")
	mockRepo.EXPECT().
		FindUser(gomock.Any()).
		Return("", expectedErr).
		Times(1)

	_, err := service.GetGreeting("unknown-user")
	if err == nil {
		t.Fatal("expected error from GetGreeting, got nil")
	}
	if !errors.Is(err, expectedErr) {
		t.Fatalf("expected error wrapping %v, got %v", expectedErr, err)
	}
}

Seeder d'origine

anonyme