title: Golang Unit Testing: error conditions
body: <p>How do I test error conditions, &amp; other unexpected code flow, in Golang?</p>
  
  <p>Suppose I have code as follows:</p>
  
  <pre><code>import crypto
  func A(args) error {
      x, err := crypto.B()
      if err != nil {
          return err
      }
      return nil
  }
  </code></pre>
  
  <p><code>B</code> is some function. I believe that the only way for me to test this failure scenario is to change the value of <code>B</code> for my test (mock it so it returns an error). Things I have tried:</p>
  
  <p>1) monkeypatch the function just before the test and unpatch afterwards.
  This was a horrible idea. Caused all sorts of weird issues as the
  tests were running.</p>
  
  <p>2) Pass <code>B</code> as an argument to <code>A</code>. This is all well and good but it also
  means that I have to change the definition for <code>A</code> and then update
  every use of it every time the implementation changes. Furthermore,
  <code>A</code> may be using many imported functions and putting them all in the
  type definition for <code>A</code> just seems ugly and not idiomatic.</p>
  
  <p>3) Change the value of <code>B</code> for my test, then change it back.</p>
  
  <pre><code>import crypto.B
  cryptoB = crypto.B
  func A(args) error {
      x, err := cryptoB()
      if err != nil {
          return err
      }
      ...
   }
  
   func Test_A(t *testing.T) {
       oldB := cryptoB
       cryptoB = mockB
       // run test
       cryptoB = oldB
       ...
   }
  </code></pre>
  
  <p>I've been using method #3 as it allows me fine grained unit testing control while not creating too much overhead. That said, it's ugly and causes confusion e.g. "Why are we renaming all of the imported functions?".</p>
  
  <p>What should I be doing? Please help me so my codes can be more better :)</p>