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. SoObjhave 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.
Why you think you should mock
Second? (sorry for starting with a question)When you test you should focus on observable behavior (test public interface), from the test point of view it is not important what is called behind the scenes. If
Secondon its own does not form a dependency, does it have to be public? If it is a part of bigger feature in my opinion you should accept that, from test/user point of view it is unobservable implementation detail that you call it fromFirst.