Skip to content

Instantly share code, notes, and snippets.

@phritz
Created February 19, 2018 19:33
Show Gist options
  • Save phritz/563f2a836f023343ecdbba760630c6fe to your computer and use it in GitHub Desktop.
Save phritz/563f2a836f023343ecdbba760630c6fe to your computer and use it in GitHub Desktop.
pure function DI pattern
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
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