gogomock

Mocking a non-interface function


I have a Go code something like this

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
}

I want to write unit test case for SetRequestMap .

How can I mock checkStatusOnline without implementing any extra functions for mock?


Solution

  • One way you can mock such functions is using function pointers:

    var checkStatusOnline = defaultCheckStatusOnline
    
    func defaultCheckStatusOnline(...) {... }
    

    During a test run, you can set checkStatusOnline to a different implementation to test different scenarios.

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