dpvmtdu364462 2017-10-26 00:37
浏览 331

如何在golang中向httptest.server注入URL?

For sentence

resp, err := client.Get(fmt.Sprintf("https://www.xxxxx/day?time=%s", time))

If I want to mock a response to this client.Get() in unit test, I should use httptest.server, but how can I bind the url (https://www.xxxxx/day?time=%s) to the url of httptest.server? so that when I call client.Get() it can return the response I set before. For some reason I cannot mock a client here.

  • 写回答

3条回答 默认 最新

  • dpruwm6206 2017-10-26 07:56
    关注

    The http.Client is a struct not an interface which makes mocking it difficult as you have seen. An alternative way of mocking it is passing in the external dependencies that a routine needs, so instead of directly using client.Get, you use clientGet - which is a function pointer that was handed into the routine.

    From the unit test you can then create :

    mockClientGet(c *http.client, url string) (resp *http.Response, err error) {
    // add the test code to return what you want it to.
    }
    

    Then in your main code use:

    resp, err := clientGet(client, fmt.Sprintf("https://www.xxxxx/day?time=%s", time))
    

    When calling the procedure normally, use the function pointer to http.Client.Get, and for your test pass in a pointer to your mock. It's not ideal, but I've not seen a nicer way around mocking non-interface external calls - and given its an external dependency, injecting it from the outside is not a bad thing.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题