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

huangapple go评论85阅读模式
英文:

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

问题

在golang中,我经常看到一个成员函数调用同一对象的另一个成员函数。例如,看下面的golang代码:

type Obj struct{}

func (o Obj) First() {
    // 做一些事情
    o.Second()
}

func (o Obj) Second() {
    // 做另一些事情
}

你会如何为函数First编写单元测试? 如果你为上述代码中的函数"First"编写单元测试,你会如何模拟函数"Second"?

为了解决这个问题,我可以提出以下可能性:

  1. 函数Second()可能是另一个对象的责任,即Obj的依赖项。所以Obj承担了比它应该承担的更多责任。
  2. 将对象作为参数传递给First()进行快速修复(这将永远存在于代码中)。看起来不太好。
func First(o Obj) {
    // 做一些事情
    o.Second()
}
  1. First()添加一个接口类型的参数,该接口提供了Second()的行为。

但是,我陷入了一个情况,为了可读性将First()拆分为更小的函数。Second()无法简单地移到其他对象中。

英文:

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

得分: 1

你为什么认为你应该模拟Second?(抱歉一开始就问问题)

当你进行测试时,应该关注可观察的行为(测试公共接口),从测试的角度来看,重要的是背后调用了什么。如果Second本身不形成依赖关系,它是否必须是公共的?如果它是一个更大功能的一部分,在我看来,你应该接受这一点,从测试/用户的角度来看,你从First调用它是不可观察的实现细节。

英文:

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.

huangapple
  • 本文由 发表于 2023年4月28日 22:09:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76130444.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定