title: how can you stub calls to GitHub for testing?
body: <p>I need to create a Pull Request comment using go-github, and my code works, but now I'd like to write tests for it (yes, I'm aware that tests should come first), so that I don't actually call the real GitHub service during test.</p>
  <p>I've read 3 blogs on golang stubbing and mocking, but, being new to golang, I'm a bit lost, despite <a href="https://github.com/google/go-github/issues/113" rel="nofollow noreferrer">this discussion on go-github issues</a>. For example, I wrote the following function:</p>
  <pre class="lang-golang prettyprint-override"><code>// this is my function
  func GetClient(token string, url string) (*github.Client, context.Context, error) {
      ctx := context.Background()
      ts := oauth2.StaticTokenSource(
          &amp;oauth2.Token{AccessToken: token},
      )
      tc := oauth2.NewClient(ctx, ts)
      client, err := github.NewEnterpriseClient(url, url, tc)
  
      if err != nil {
          fmt.Printf(&quot;error creating github client: %q&quot;, err)
          return nil, nil, err
      }
      return client, ctx, nil
  }
  </code></pre>
  <p>How could I stub that?</p>
  <p>Similarly, I have this:</p>
  <pre class="lang-golang prettyprint-override"><code>func GetPRComments(ctx context.Context, client *github.Client) ([]*github.IssueComment, *github.Response, error)  {
      opts := &amp;github.IssueListCommentsOptions{
          ListOptions: github.ListOptions{
              Page:    1,
              PerPage: 30,
          },
      }
      githubPrNumber, err := strconv.Atoi(os.Getenv(&quot;GITHUB_PR_NUMBER&quot;))
      if err != nil || githubPrNumber == 0 {
        panic(&quot;error: GITHUB_PR_NUMBER is not numeric or empty&quot;)
      }
  
      // use Issues API for PR comments since GitHub docs say &quot;This may seem counterintuitive... but a...Pull Request is just an Issue with code&quot;
      comments, response, err := client.Issues.ListComments(
            ctx,
            os.Getenv(&quot;GITHUB_OWNER&quot;),
            os.Getenv(&quot;GITHUB_REPO&quot;),
            githubPrNumber,
            opts)
      if err != nil {
          return nil, nil, err
      }
      return comments, response, nil
  }
  
  </code></pre>
  <p>How should I stub that?</p>
  <p>My thought was to perhaps use dependency injection by creating my own structs first, but I'm not sure how, so currently I have this:</p>
  <pre class="lang-golang prettyprint-override"><code>func TestGetClient(t *testing.T) {
      client, ctx, err := GetClient(os.Getenv(&quot;GITHUB_TOKEN&quot;), &quot;https://example.com/api/v3/&quot;)
      c, r, err := GetPRComments(ctx, client)
      ...
  }
  </code></pre>