我刚开始做一个简单的小项目+做测试的习惯来学习。但是我在使用模拟设置测试时遇到了困难。特别是在设置模拟对象时。
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感谢所有的帮助..。谢谢!
发布于 2014-03-07 21:44:23
我不是一个gomock专家,但是在阅读了gomock GoDoc页面之后,我发现了您的代码中的几个问题。首先,显然不能使用gomock来模拟包函数(就像您试图使用sample.GetResponse时所做的那样),只能使用接口。第二,根据“标准用法”,你必须
发布于 2019-09-26 17:06:28
测试和覆盖范围:
有关如何使用mockgen为我们的接口生成模拟的更多信息,请参考mockgen命令的示例mockgen https://github.com/golang/mock来生成模拟接口文件->。
mockgen -destination={put the generated mocks in the file} -package={generate mocks for this package} {generate mocks for this interface}有关更多信息,请参阅--> https://blog.codecentric.de/en/2017/08/gomock-tutorial/
https://stackoverflow.com/questions/22260037
复制相似问题