小编sar*_*roz的帖子

如何在Go中使用gomock模拟一个函数?

我是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") …
Run Code Online (Sandbox Code Playgroud)

testing mocking go

4
推荐指数
2
解决办法
5217
查看次数

标签 统计

go ×1

mocking ×1

testing ×1