Created
February 19, 2018 19:33
-
-
Save phritz/563f2a836f023343ecdbba760630c6fe to your computer and use it in GitHub Desktop.
pure function DI pattern
This file contains 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
package example | |
// This is the function you want to test. It has as a depdendency a pure | |
// function, foo, that you would like to control for tests. | |
func doSomeWork() int { | |
y := 0 | |
// ... | |
x := fooFunc(y) | |
// ... | |
return x | |
} | |
// This is the dependency | |
func foo(x int) int { | |
// ... | |
// do the thing for real | |
// ... | |
return x | |
} | |
// This is the seam, you swap it out in tests. | |
var fooFunc = foo |
This file contains 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
package example | |
func fakeFoo(x int) int { | |
// The fake/mock/stub functionality goes here | |
return 0 | |
} | |
func TestDoSomeWork() { | |
oldFooFunc := fooFunc | |
fooFunc = fakeFoo | |
defer func() { fooFunc = oldFooFunc }() | |
// Here write tests for doSomeWork, which now uses fakeFoo | |
assert.True(doSomeWork() == ...) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment