How to write unit test when a member function is calling another member function of the same object in golang?

626 Views Asked by At

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:

  1. Function Second() might be responsibility of another object i.e. a dependency of Obj. So Obj have more responsibilities than it should have.
  2. 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()
}

  1. Add an Interface type as argument to First() which provides behaviour Second()

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.

1

There are 1 best solutions below

0
mleko On

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 Second on 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 from First.