【发布时间】:2014-03-07 20:26:48
【问题描述】:
我是 Go 新手,正在做一个简单的小项目 + 做测试习惯来学习.. 但是我在使用 mock 设置测试时遇到了麻烦。特别是在设置模拟对象时
sample/sample.go
package sample
import (
"fmt"
"net/http"
)
func GetResponse(path, employeeID string) string {
url := fmt.Sprintf("http://example.com/%s/%s", path, employeeID)
// made some request here
// then convert resp.Body to string and save it to value
return value
}
func Process(path, employeeID string) string {
return GetResponse(path, employeeID)
}
sample/sample_test.go
package sample_test
import (
"testing"
"github.com/example/sample" // want to mock some method on this package
)
func TestProcess(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
sample.MOCK()SetController(ctrl)
sample.EXPECT().GetResponse("path", "employeeID").Return("abc")
v := sample.GetResponse("path", "employeeID")
fmt.Println(v)
}
每次我用
运行它go test
我总是出错
undefined: sample.MOCK
undefined: sample.EXPECT
谁能指出我做错了什么?我需要先初始化一个模拟对象吗?在模拟方法之前?
如果我将 GetResponse 设为私有 [getResponse],我将无法模拟它,对吗?
感谢所有帮助.. 谢谢!
【问题讨论】:
-
golang.org/pkg/net/http/httptest 是测试与外部服务对话的代码的好方法。它让您可以自然地编写代码,并让您的测试实际测试您的代码,而不是一些模拟出来的代码。