Last active
August 29, 2015 14:19
-
-
Save ellotheth/350f9b1391728cc80b86 to your computer and use it in GitHub Desktop.
Mockable interface methods in Go, maybe
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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