go - 模拟非接口(interface)函数

标签 go gomock

我有一个像这样的 Go 代码

func (r *Request) SetRequestMap(ctx *gin.Context, data map[string]interface{}) *Request {
    
    //Some processing code
     
     id, ok := r.map["id"]
    
    if !ok {
        return r
    }

    checkStatus := checkStatusOnline(ctx, id) // checkStatusOnline returns "on" if id is present or "off".
    // It make use of HTTP GET request internally to check if id is present or not. 
    // All json unmarshal is taken care of internally

    if checkStatus == "on" {
        r.map["val"] = "online"
    }

    return r
}
我想为 SetRequestMap 编写单元测试用例.
我如何模拟 checkStatusOnline没有为模拟实现任何额外的功能?

最佳答案

模拟此类函数的一种方法是使用函数指针:

var checkStatusOnline = defaultCheckStatusOnline

func defaultCheckStatusOnline(...) {... }
在测试运行期间,您可以设置 checkStatusOnline到不同的实现来测试不同的场景。
func TestAFunc(t *testing.T) {
   checkStatusOnline=func(...) {... }
   defer func() {
      checkStatusOnline=defaultCheckStatusOnline
   }()
   ...
}

关于go - 模拟非接口(interface)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63016942/

相关文章:

go - Golang 中是否有命令行工具来仅检查我的源代码的语法?

go - 如何测试在 goroutine 中调用了一个函数?

unit-testing - 在 Go 单元测试中使用两个不同的模拟

unit-testing - 如何比较/匹配模拟中的闭包?

ubuntu - Gogs 构建失败并显示 "no buildable Go source files"

go - 使用 channel 进行请求-响应通信的惯用方式

json - 使用 golang 将 xml 转换为 swagger 2.0 规范

go - panic : runtime error: makeslice: cap out of range

unit-testing - 测试和模拟一个不返回任何值的函数

go - 查找模块的版本