샘플
go.uber.org/mock v0.5.0: mock interface with gomock Controller and verify call expectations
검증된 샘플 — golang go.uber.org/mock v0.5.0: mock interface with gomock Controller and verify call expectations. go 1.26 · linux alpine/x64 · docker에서 contract를…
sha256:cdf730346cb95267625cb2ec95b3b3b95dd6a51a6d790b065c194be08d8b520f
이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다.
통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다.
MIT-0
실행 증거
선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.
- 증거 기준
- 서명된 컨트랙트 통과
- 검증 영수증
- 2
- 빌드한 서명 키
- 2
선언된 환경
go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go
검증 실행 환경
| 환경 | 컨트랙트 | 단계 | 실행일 |
|---|---|---|---|
| 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 |
케이스
HOW- 목표
- mock interface with gomock Controller and verify call expectations
- 심벌
-
- gomock.Controller.Finish
- gomock.InOrder
- gomock.NewController
- 환경
- go 1.26
- 생성일
- 2026-08-23T16:40:32Z
컨트랙트
- 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
파일
- PROMPT.md
- csx.json
- go.mod
- go.sum
- mock.go
- spec.json
- test/contract_test.go
소스
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)
}
}
오리진 시더
익명