最近想学习一下 TDD,在网上找到了一篇文章
learn-go-with-tests
中间使用了依赖注入方式来预留给测试进行 MOCK,这部分我怎么看怎么感觉别扭,如果我需要根据 if else 初始化不同的资源呢?
func Exec(v1 int, v2 string) int {
count := 0
if v1 > 10 {
q := NewQuery()
q.Query(v1)
count += 1
}
if strings.HasPrefix(v2, "a") {
d := NewUpdate()
d.Update(v2)
count += 2
}
return count
}
如果要使用依赖注入,是要改成下面的样子么?
func ExecDI(v1 int, v2 string, q QueryModule, d UpdateModule) int {
count := 0
if v1 > 10 {
q.Query(v1)
count += 1
}
if strings.HasPrefix(v2, "a") {
d.Update(v2)
count += 2
}
return count
}
那如果子模块也有资源需要初始化,那也要从最顶层传进去么?
func ExecDIDI(v1 int, v2 string, q QueryModule, d UpdateModule, configs config.Config, db *sql.DB) int {
count := 0
if v1 > 10 {
q.QueryDI(v1, configs)
count += 1
}
if strings.HasPrefix(v2, "a") {
d.UpdateDI(v2, db)
count += 2
}
return count
}
假设一个偏远的代码分支需要从 Http 获取一些数据,本来只要执行到分支这里的时候,再让它自行去获取就好。
那改成依赖注入会变成从一开始就要获取么?
如果还是保留这部分不注入,那么这部分代码块就没法 mock 以进行充分的测试了