dongzhou4727 2016-10-31 08:45
浏览 27
已采纳

如果直接访问结构,如何模拟结构

I am writing a program that acts as a client of Github API. I use https://github.com/google/go-github to access the API. I have a function that accepts a github.Client as one of the argumenta and uses it to retrieve commits from a pull request. I want to test this function with some fake data.

In the article here: https://nathanleclaire.com/blog/2015/10/10/interfaces-and-composition-for-effective-unit-testing-in-golang/ I read, that I should create an interface that would be implemented by github client, and then in my tests, create a mock that would also implement it. My problem is, that go-github uses the following semantics to retrieve pull request:

prs, resp, err := client.PullRequests.List("user", "repo", opt)

The interfaces however allow you to specify methods that should be implemented, but not fields. So how can I mock the github.Client object so it can be used in the above semantics?

  • 写回答

1条回答 默认 最新

  • douqiang1851 2016-10-31 17:35
    关注

    It may not be practical in your case, especially if you're using a lot of functionality from github.Client but you can use embedding to create a new structure that implements an interface you define.

    type mockableClient struct {
        github.Client
    }
    
    func (mc *mockableClient) ListPRs(
    owner string, repo string, opt *github.PullRequestListOptions) (
    []*github.PullRequest, *github.Response, error) {
    
    return mc.Client.PullRequests.List(owner, repo, opt)
    }
    
    
    type clientMocker interface {
        Do(req *http.Request, v interface{}) (*github.Response, error)
    
        ListPRs(string,string,*github.PullRequestListOptions) (
    []*github.PullRequest, *github.Response, error)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能