sar*_*roz 4 testing mocking go
我是Go的新手并做一个简单的小项目+做测试习惯学习..但我在使用mock设置测试时遇到了麻烦.特别是在设置模拟对象时
采样/ 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)
}
Run Code Online (Sandbox Code Playgroud)
采样/ 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)
}
Run Code Online (Sandbox Code Playgroud)
我每次都跑这个
go test
Run Code Online (Sandbox Code Playgroud)
我总是得到错误
undefined: sample.MOCK
undefined: sample.EXPECT
Run Code Online (Sandbox Code Playgroud)
任何人都可以指出我做错了什么?我需要先初始化一个模拟对象吗?在嘲笑这个方法之前?
如果我将GetResponse设为私有[getResponse],我将无法模拟它吗?
感谢所有的帮助..谢谢!
我不是gomock专家,但在阅读gomock GoDoc页面后,我发现你的代码有几个问题.首先,您显然无法使用gomock来模拟包函数(正如您尝试使用sample.GetResponse),只能使用接口.其次,根据"标准用法",你必须
小智 5
测试和覆盖范围:
\n\n有关如何使用mockgen为我们的接口生成模拟的更多信息,请参阅 \xe2\x86\x92 https://github.com/golang/mock \nan 生成模拟接口文件的mockgen命令示例 ->
\n\nmockgen -destination={put the generated mocks in the file} -package={generate mocks for this package} {generate mocks for this interface}\nRun Code Online (Sandbox Code Playgroud)\n\n有关更多信息,请参阅 --> https://blog.codecentric.de/en/2017/08/gomock-tutorial/
\n