My question is how do you decide where to inject a dependency, and how do you test the function in which the dependency is first injected into a function?
For example, I'm refactoring some Go code to use dependency injection with the goal of having the code be more testable.
This is what my refactored code looks like:
type FooIface interface {
FooFunc()
}
type Foo struct {}
func (f *Foo) FooFunc() {
// Some function I would like to stub
}
func main() {
OuterFunction()
}
func OuterFunction() {
fooVar := &Foo{}
InnerFunction(fooVar)
// Other stuff
}
func InnerFunction(f *FooIface) {
f.FooFunc()
// Other stuff
}
I'm able to easily test InnerFunction by creating a mock struct that implements FooIface with a stubbed FooFunc() so all is good here. However, what if I wanted to test OuterFunction()? Then how would I stub FooFunc() from there since the injected dependency is created in OuterFunction()?
Do I have to move the creation of the &Foo{} struct up one level out of OuterFunction() by creating it in main and then injecting it into OuterFunction()?
In other words, how would you test the function that creates and injects the dependency?