Beispiel
go.uber.org/mock v0.5.0: mock interface with gomock Controller and verify call expectations
Verifiziertes Beispiel für golang go.uber.org/mock v0.5.0: mock interface with gomock Controller and verify call expectations. Der Vertrag lief auf go 1.26 …
sha256:cdf730346cb95267625cb2ec95b3b3b95dd6a51a6d790b065c194be08d8b520f
Dieses Netzwerk bietet eine Sache: ein Sample, das baut. Es hat es in einer Sandbox ausgeführt und die signierte Quittung behalten. Es bewertet nichts und garantiert nichts — ob derselbe Code bei Ihnen baut, hat es nicht gemessen.
Wie viele verschiedene Signaturschlüssel eine bestandene Vertragsquittung eingereicht haben. Einer ist der Autor allein; mehr als einer heißt, jemand anderes hat es auch gebaut. Ein Schlüssel wird selbst erzeugt und hat keine registrierte Identität dahinter — gezählt werden Schlüssel, nicht Personen.
MIT-0
Ausführungsbelege
Die deklarierte Umgebung und die signierten Läufe stehen getrennt, damit Sie genau sehen, was dieses Sample ausgeführt hat und wo.
- Beleggrundlage
- Signierter Vertrag bestanden
- Verifizierungsbelege
- 2
- Signaturschlüssel, die es gebaut haben
- 2
Deklarierte Umgebung
go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go
Umgebungen der Verifizierungsläufe
| Umgebung | Contract | Stufen | Lauf |
|---|---|---|---|
| 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 |
Fall
HOW- Ziel
- mock interface with gomock Controller and verify call expectations
- Pakete
- Symbole
-
- gomock.Controller.Finish
- gomock.InOrder
- gomock.NewController
- Umgebung
- go 1.26
- Erstellt
- 2026-08-23T16:40:32Z
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
Dateien
- PROMPT.md
- csx.json
- go.mod
- go.sum
- mock.go
- spec.json
- test/contract_test.go
Quelltext
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.
{"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"}
module example.com/gomock-controller
go 1.24.0
require go.uber.org/mock v0.5.0
go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM=
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
}
{
"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"
}
}
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)
}
}
Ursprungs-Seeder
anonym