模拟非接口功能

时间:2020-07-21 14:37:11

标签: 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而不实现任何额外的模拟功能?

2 个答案:

答案 0 :(得分:1)

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

var checkStatusOnline = defaultCheckStatusOnline

func defaultCheckStatusOnline(...) {... }

在测试运行期间,您可以将checkStatusOnline设置为不同的实现,以测试不同的场景。

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

答案 1 :(得分:0)

您可以执行此操作以模拟功能。

// 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
}
相关问题