Mocking a non-interface function

1.2k views Asked by At

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?

2

There are 2 answers

0
Burak Serdar On BEST ANSWER

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
   }()
   ...
}
0
poWar On

You can do this to mock the function.

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