Skip to content

Instantly share code, notes, and snippets.

@ellotheth
Last active August 29, 2015 14:19
Show Gist options
  • Save ellotheth/350f9b1391728cc80b86 to your computer and use it in GitHub Desktop.
Save ellotheth/350f9b1391728cc80b86 to your computer and use it in GitHub Desktop.
Mockable interface methods in Go, maybe
type InterfaceThing interface {
MockableMethod() int
TalksToMockableMethod() bool
}
func MockableMethod() int {
// i do things that are annoying to test, like run exec.Cmd or talk to a database!
return 0
}
// implements part of the interface
type ParentThingWithMockableMethod struct {
mockableMethod func() int
}
func (t *ParentThingWithMockableMethod) MockableMethod() int {
return t.mockableMethod()
}
// implements the whole interface, with Parent's MockableMethod
type ChildThing struct {
ParentThingWithMockableMethod
}
func NewChildThing() *ChildThing {
thing := &ChildThing{}
thing.mockableMethod = MockableMethod
return thing
}
func (c *ChildThing) TalksToMockableMethod() bool {
return c.MockableMethod() > 0
}
func TestTalksToMockableMethod(t *testing.T) {
thing := ChildThing{
ParentThingWithMockableMethod{
mockableMethod: func() { return 1 }
}
}
assert.True(t, thing.TalksToMockableMethod())
thing.mockableMethod = func() { return -1 }
assert.False(t, thing.TalksToMockableMethod())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment