duanduo7400 2018-06-07 02:55
浏览 2
已采纳

作证在函数内部模拟函数返回

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?

  • 写回答

1条回答 默认 最新

  • douxuelv7755 2018-06-07 03:55
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#.net#的问题:End Function
  • ¥50 用AT89C52单片机设计一个温度测量与控制电路
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用
  • ¥20 51单片机学习中的问题
  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题