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?
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)
}