-1

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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Vatz
  • 11
  • 5

2 Answers2

1

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
   }()
   ...
}
Burak Serdar
  • 46,455
  • 3
  • 40
  • 59
0

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
}
poWar
  • 745
  • 6
  • 15