基本的概念就是這樣子:
1. 在 Golang 裡,可以被重新定義的東西就是 global variable 。
2. 如果要測的某個函數,它本身沒有寫好依賴注入之類的東西,又恰好呼叫了一個有 complex dependency 的函數。就把這個有 complex dependency 的函數用 global variable 來加上一層間接性。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
func bar() { | |
fmt.Println("bar is a function with complex dependency") | |
} | |
var bar_impl func() = bar | |
func foo() { | |
bar_impl() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"testing" | |
) | |
func simple() { | |
fmt.Println("simple dependency.") | |
} | |
func init() { | |
// golang version of with-redefs | |
bar_impl = simple | |
} | |
func TestFoo(t *testing.T) { | |
foo() | |
} |