You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I think we could give a more powerful ability to go test (xxx_test.go), that we can create a mock function or a mock struct, and inject it and replace original symbol at compile phase. So we have a more flexible way to write the codes, not worry about "hardwire" function or struct in codes. Otherwise, we need to interface everything, just for testing and mock the object.
--------------------------------------------
download_test.go
--------------------------------------------
//inject/mock get
func get(url string) string {
return string("hello world!")
}
func TestDownloader(t *testing.T){
res := downloader()
if res != "hello world!" {
t.Error("fail")
}
}
Sorry, I'm not a native speaker. Hope I explained my idea clearly.
The text was updated successfully, but these errors were encountered:
The testing package is deliberately minimal and avoids magic code rewriting like this. For complex cases there is the gomock tool, although it is a bit heavy-weight to use. In this specific case, where you want to override code you wrote, you can add to it (in the real copy of the code):
var getHook func(string) string
func get(url string) string {
if getHook != nil { return getHook(url) }
... real code
}
and then in your test you can have your specific test case set and restore getHook:
func Test(t *testing.T) {
getHook = myGet
defer func() { getHook = nil }()
... your test ...
}
When I use go test for unit test, I found it is hard (maybe no way) to mock a function or a struct object inside a struct.
I think we could give a more powerful ability to go test (xxx_test.go), that we can create a mock function or a mock struct, and inject it and replace original symbol at compile phase. So we have a more flexible way to write the codes, not worry about "hardwire" function or struct in codes. Otherwise, we need to interface everything, just for testing and mock the object.
Sorry, I'm not a native speaker. Hope I explained my idea clearly.
The text was updated successfully, but these errors were encountered: