gotestify

Testify Mock a function return inside a function


I would like to Mock the response of a function. But this function is located or called inside another function. Let say I have this function

// main.go
func TheFunction() int {
   // Some code
   val := ToMockResponse()
   return val
}

func ToMockResponse() int {
    return 123
}

Now on my test file

// main_test.go
func TestTheFunction(t *testing.T) {
    mockInstance = new(randomMock)
    mockInstance.On("ToMockResponse").Return(456)

    returned := TheFunction()
    assert.Equal(t, 456, returned)
}

As you can see within function TheFunction() a call to function ToMockResponse is made. Now I would like to test TheFunction but I would like to Mock the response of ToMockResponse how can I achieve this?


Solution

  • You should consider passing in the second function is as an parameter to the first.

    You have a few options for doing that. You could simply pass it as a parameter.

    func DoX(doY func()) {
       doY()
    }
    

    That’s simple but doesn’t work well as the core get more complex. The better alternative is often to make the functions methods on a struct.

    type X struct {
       Y Y
    }
    
    type Y interface {
       Do()
    }
    
    func (x *X) Do() {
       x.Y.Do()
    }
    

    Then Y can be replaced with a mock.