Let's say I have this code and I want to create a test for Foo()
The important part it Foo makes a call to Bar
package main
type MyInterface interface {
Foo() error
Bar() error
}
type MyStruct struct {
}
func NewMyStruct() MyInterface{
return &MyStruct{}
}
func (m *MyStruct) Foo() error {
// do something
m.Bar()
// do something else
return nil
}
func (m *MyStruct) Bar() error {
// do something
return nil
}
Is it possible to create a test for this where I can mock the behaviour of Bar before I run Foo? or am I doing something fundamentally wrong?
I can see that if I extracted Bar into its own service I would mock it that way but that also doesn't feel right.
Any insights or links to documentation would be great.
You should be able to achieve what you need with a couple of changes. First, let me present the code and then I'll walk you through all of the relevant changes.
main.gofileHere, I changed a couple of things in order to be able to successfully mock our dependencies. Let me recap them:
MyStructhas a dependency of typeMyInterfaceNewMyStructaccepts the interface as parameter and returns a pointer to theMyStructstructFoomethod, we're going to rely on theDSfield of our pointer receiver type instanceNow, let's switch to the test file.
main_test.gofileHere, I found it best to add comments within the code to give you a chronological order of what's going on. The idea is that the real system tested (e.g. the
sutvariable) is relying on mock instead of actual implementations. Thanks to the methodTimes, we make sure that theBarmethod is called once.I always used this approach when it comes to testing production code and I find it pretty flexible and amazing!
Let me know if this helps you or if you still need something else, thanks!