duanjing1023 2014-03-07 20:26
浏览 161

如何在Go中使用gomock模拟功能?

I am new to Go and doing small simple project + doing testing habit to learn.. but I am having trouble in setting up test using mock. Specifically in setting up the mock object

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)
}

Everytime I run this with

go test

I always get error

undefined: sample.MOCK
undefined: sample.EXPECT
  1. Anyone could point out what am I doing wrong? do I need to initialize a mock object first? before mocking the method?

  2. If I make GetResponse to be private [getResponse], I wont be able to mock it right?

Appreciate the all help.. Thanks!

  • 写回答

2条回答 默认 最新

  • dongnue2071 2014-03-07 21:44
    关注

    I am not a gomock expert, but after reading the gomock GoDoc page, I see several issues with your code. First, you apparently can't use gomock to mock package functions (as you are trying to do with sample.GetResponse), only interfaces. Second, according to "standard usage", you have to

    1. define an interface (e.g. FooInterface) that you want to mock
    2. use mockgen to generate a mock from that interface
    3. create a mockObj using the function NewMockFooInterface()
    4. mockObj will then have the methods you want to call (i.e. EXPECT())
    评论

报告相同问题?

悬赏问题

  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题