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 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误