In golang, I often see a member function calling another member function of the same object. For example check following golang code:
type Obj struct{}
func (o Obj) First() {
// do something
o.Second()
}
func (o Obj) Second() {
// do another thing
}
How would you write unit test for function First
? If you write unit test for function "First" in above code, how would you mock the function "Second" ?
To fix this, I could come up with following possibilities:
- Function
Second()
might be responsibility of another object i.e. a dependency ofObj
. SoObj
have more responsibilities than it should have. - Pass the Object to
First()
as argument for a quick fix (which ends up forever in the code). Doesn't look good.
func First(o Obj) {
// do something
o.Second()
}
- Add an Interface type as argument to
First()
which provides behaviourSecond()
But, I've ended up in a situation where I broke down First()
into smaller functions for the sake of readability. The Second()
simply can't be taken out to some other object.