Go 模拟非接口函数

Go 模拟非接口函数,go,gomock,Go,Gomock,我有一个类似这样的密码 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 := checkStatusO

我有一个类似这样的密码

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编写单元测试用例


如何在不为mock实现任何额外函数的情况下模拟checkStatusOnline?

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

var checkStatusOnline = defaultCheckStatusOnline

func defaultCheckStatusOnline(...) {... }
在测试运行期间,您可以将checkStatusOnline设置为不同的实现,以测试不同的场景

func TestAFunc(t *testing.T) {
   checkStatusOnline=func(...) {... }
   defer func() {
      checkStatusOnline=defaultCheckStatusOnline
   }()
   ...
}

您可以这样做来模拟函数

// Code

var checkStatusOnline = func(ctx context.Context, id int) int {
    ...
}

// Test

func TestSetRequestMap(t *testing.T) {
    tempCheckStatusOnline := checkStatusOnline
    checkStatusOnline = func(ctx context.Context, id int) int {
        // mock code
    }
    defer checkStatusOnline = tempCheckStatusOnline

    // Test here
}

将函数作为参数传入