Skip to content

Instantly share code, notes, and snippets.

@patrickmscott
Created November 2, 2018 15:06
Show Gist options
  • Save patrickmscott/c63c1d4b5159a76b584e96968799569f to your computer and use it in GitHub Desktop.
Save patrickmscott/c63c1d4b5159a76b584e96968799569f to your computer and use it in GitHub Desktop.
Longer example
type PayrollModel interface {
GetPayrollForCustomerID(context.Context, CustomerID) (*Payroll, error)
InsertOrUpdatePayroll(context.Context, UpsertPayrollInput) error
}
type payrollModelImpl struct {
dbx db.SQLExecutor
}
func (impl *payrollModelImpl) GetPayrollForCustomerID(ctx context.Context, CustomerID) (*Payroll, error) {
return impl.dbx.Select(...)
}
func (impl *payrollModelImpl) InsertOrUpdatePayroll(ctx context.Context, input UpsertPayrollInput) error {
if input.SomeField.IsIncluded() {
// ...
}
impl.dbx.Upsert(...)
return nil
}
func TestWithMock(t *testing.T) {
// Setup gomock controller to verify expected calls, etc.
ctrl := gomock.NewController(t)
defer ctrl.Finish()
// Create a mock implementation to record expected calls and return values.
modelImpl := NewMockPayrollModel(ctrl)
modelImpl.EXPECT().GetPayrollForCustomerID(context.Background(), "some id").Return("test payroll", nil)
payrollService := payroll_service.NewPayrollService(modelImpl)
payrollService.DoRealStuffWithPayroll(...)
// The defer statement above will FAIL if expected calls are missing.
}
func RealCode() {
dbx := db.ConnectToRealDatabase()
payrollService := payroll_service.NewPayrollService(newPayrollModel(dbx))
payrollService.DoRealStuffWithPayroll(...)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment