【发布时间】:2017-02-23 17:45:22
【问题描述】:
我很难找到一种在 golang 中编写可测试代码的惯用方式。我了解接口的重要性及其在测试中的用途,但我还没有弄清楚如何模拟/测试外部结构依赖项。
作为示例,我编写了以下代码,它模拟了在 GitHub 上创建拉取请求的包装器。
type GitHubService interface {
}
type gitHubService struct {
CreatePullRequest(...) (PullRequest,error)
}
func (s gitHubService) CreatePullRequest(...) (PullRequest,error) {
tp := github.BasicAuthTransport{
Username: strings.TrimSpace(/*.....*/),
Password: strings.TrimSpace(/*.....*/),
}
client := github.NewClient(tp.Client())
pr,err := client.Repositories.CreatePullRequest(...)
...
}
func TestPullRequest(t *testing.T) {
service := gitHubService{}
pr,err := service.CreatePullRequest(...)
...
}
如果我正在为 GitHubService.CreatePullRequest(...) 编写单元测试,我想模拟对 client.Repositories.CreatePullRequest(...) 的调用,甚至可能模拟对 github.NewClient(...) 的调用,以返回我可以控制的模拟实现。
使用诸如gomock 之类的工具,您似乎对结构和包函数不走运。
处理这个问题的惯用方法是什么?我对控制反转以及依赖注入和服务定位器等不同模式非常熟悉,但我无数次听到这不是惯用的。
【问题讨论】:
-
单元测试应该单独测试
CreatePullRequest的逻辑,我对集成测试不感兴趣。 -
我的意思是这里没有逻辑可以测试——一切都发生在 github 包中,它有自己的测试。如果您确实在
...s 后面隐藏了其他逻辑,则将其拆分为单独的部分进行测试。 -
@JimB 如果我将
...背后的逻辑拆分为自己的测试,我正在测试这些东西,而不是CreatePullRequest(...)中的逻辑。我仍然想要一个单元测试来测试这个代码单元的逻辑流。
标签: unit-testing go