title: Mock functions in Go
body: <p>I'm puzzled with dependencies. I want to be able to replace some function calls with mock ones. Here's a snippet of my code:</p>
  <pre><code>func get_page(url string) string {
      get_dl_slot(url)
      defer free_dl_slot(url)
      
      resp, err := http.Get(url)
      if err != nil { return &quot;&quot; }
      defer resp.Body.Close()
      
      contents, err := ioutil.ReadAll(resp.Body)
      if err != nil { return &quot;&quot; }
      return string(contents)
  }
  
  func downloader() {
      dl_slots = make(chan bool, DL_SLOT_AMOUNT) // Init the download slot semaphore
      content := get_page(BASE_URL)
      links_regexp := regexp.MustCompile(LIST_LINK_REGEXP)
      matches := links_regexp.FindAllStringSubmatch(content, -1)
      for _, match := range matches{
          go serie_dl(match[1], match[2])
      }
  }
  </code></pre>
  <p>I'd like to be able to test <code>downloader()</code> without actually getting a page through http - i.e. by mocking either <code>get_page</code> (easier since it returns just the page content as a string) or <code>http.Get()</code>.</p>
  <p>I found <a href="https://groups.google.com/forum/#!topic/golang-nuts/6AN1E2CJOxI" rel="noreferrer">this thread</a> which seems to be about a similar problem. Julian Phillips presents his library, <a href="http://github.com/qur/withmock" rel="noreferrer">Withmock</a> as a solution, but I'm unable to get it to work. Here's the relevant parts of my testing code, which is largely cargo cult code to me, to be honest:</p>
  <pre><code>import (
      &quot;testing&quot;
      &quot;net/http&quot; // mock
      &quot;code.google.com/p/gomock&quot;
  )
  ...
  func TestDownloader (t *testing.T) {
      ctrl := gomock.NewController()
      defer ctrl.Finish()
      http.MOCK().SetController(ctrl)
      http.EXPECT().Get(BASE_URL)
      downloader()
      // The rest to be written
  }
  </code></pre>
  <p>The test output is following:</p>
  <blockquote>
  <p>ERROR: Failed to install '_et/http': exit status 1 output: can't load
  package: package _et/http: found packages http (chunked.go) and main
  (main_mock.go) in<br />
  /var/folders/z9/ql_yn5h550s6shtb9c5sggj40000gn/T/withmock570825607/path/src/_et/http</p>
  </blockquote>
  <p>Is the Withmock a solution to my testing problem? What should I do to get it to work?</p>