我正在编写一个程序,它充当Github的客户端。我使用https://github.com/google/go-github访问API。我有一个函数,它接受一个github.Client作为and文件之一,并使用它从拉请求中检索提交。我想用一些假数据来测试这个函数。
在本文:https://nathanleclaire.com/blog/2015/10/10/interfaces-and-composition-for-effective-unit-testing-in-golang/中,我看到,我应该创建一个由github客户端实现的接口,然后在我的测试中创建一个也将实现它的模拟。我的问题是,go-github使用以下语义检索拉请求:
prs, resp, err := client.PullRequests.List("user", "repo", opt)
但是,接口允许您指定应该实现的方法,但不能指定字段。那么,我如何模拟github.Client对象,以便在上面的语义中使用它呢?
发布于 2016-10-31 17:35:35
在您的情况下,这可能不太实际,特别是当您使用github.Client的许多功能时,但是您可以使用嵌入来创建一个实现您定义的接口的新结构。
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)
}https://stackoverflow.com/questions/40338890
复制相似问题