Skip to content

Instantly share code, notes, and snippets.

@tsmaeder
Created October 14, 2016 12:22
Show Gist options
  • Save tsmaeder/5b0937a4126936b21e016a4c025c0f02 to your computer and use it in GitHub Desktop.
Save tsmaeder/5b0937a4126936b21e016a4c025c0f02 to your computer and use it in GitHub Desktop.
Mock object pattern
type WorkItemRepository struct {
DoLoad func(ctx context.Context, ID string) (*app.WorkItem, error)
DoSave func(ctx context.Context, wi app.WorkItem) (*app.WorkItem, error)
DoDelete func(ctx context.Context, ID string) error
DoCreate func(ctx context.Context, typeID string, fields map[string]interface{}) (*app.WorkItem, error)
DoList func(ctx context.Context, criteria criteria.Expression, start *int, length *int) ([]*app.WorkItem, uint64, error)
}
func (r *WorkItemRepository) Load(ctx context.Context, ID string) (*app.WorkItem, error) {
return r.DoLoad(ctx, ID)
}
func (r *WorkItemRepository) Save(ctx context.Context, wi app.WorkItem) (*app.WorkItem, error) {
return r.DoSave(ctx, wi)
}
func (r *WorkItemRepository) Delete(ctx context.Context, ID string) error {
return r.DoDelete(ctx, ID)
}
func (r *WorkItemRepository) Create(ctx context.Context, typeID string, fields map[string]interface{}) (*app.WorkItem, error) {
return r.DoCreate(ctx, typeID, fields)
}
func (r *WorkItemRepository) List(ctx context.Context, criteria criteria.Expression, start *int, length *int) ([]*app.WorkItem, uint64, error) {
return r.DoList(ctx, criteria, start, length)
}
func testFunc() {
var repo models.WorkItemRepository = &WorkItemRepository{
DoList: func(ctx context.Context, criteria criteria.Expression, start *int, length *int) ([]*app.WorkItem, uint64, error) {
return []*app.WorkItem{}, 0, nil
},
}
ts:= ...
service:= ...
newcontroller := NewWorkitemController(service, repo, ts)
}
@tsmaeder
Copy link
Author

Mock base implementation has a func field for each interface function. Member functions call the corresponding func field

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment