title: Testing log.Fatalf in go?
body: <p>I'd like to achieve 100% test coverage in go code. I am not able to cover the following example - can anyone help me with that?</p>
  <pre><code>package example
  
  import (
      &quot;io/ioutil&quot;
      &quot;log&quot;
  )
  
  func checkIfReadable(filename string) (string, error) {
      _, err := ioutil.ReadFile(filename)
      if err != nil {
          log.Fatalf(&quot;Cannot read the file... how to add coverage test for this line ?!?&quot;)
      }
      return &quot;&quot;, nil
  }
  
  func main() {
      checkIfReadable(&quot;dummy.txt&quot;)
  }
  </code></pre>
  <p>Some dumy test for that:</p>
  <pre><code>package example
  
  import (
      &quot;fmt&quot;
      &quot;testing&quot;
  )
  
  func TestCheckIfReadable(t *testing.T) {
      someResult, err := checkIfReadable(&quot;dummy.txt&quot;)
      if len(someResult) &gt; 0 {
          fmt.Println(&quot;this will not print&quot;)
          t.Fail()
      }
      if err != nil {
          fmt.Println(&quot;this will not print&quot;)
          t.Fail()
      }
  }
  
  func TestMain(t *testing.T) {
  ...
  }
  </code></pre>
  <p>The issue is that <code>log.Fatalf</code> calls <code>os.Exit</code> and go engine dies.</p>
  <ul>
  <li>I could modify the code and replace built-in library with my own - what makes the tests less reliable.</li>
  <li>I could modify the code and create a proxy and a wrapper and a .... in other words very complex mechanism to change all calls to <code>log.Fatalf</code></li>
  <li>I could stop using built-in log package... what is equal to asking &quot;how much is go built-in worth?&quot;</li>
  <li>I could live with not having 100% coverage</li>
  <li>I could replace <code>log.Fataf</code> with something else - but then what is the point for built-in <code>log.Fatalf</code>?</li>
  <li>I can try to mangle with system memory and depending on my OS replace memory address for the function (...) so do something obscure and dirty</li>
  <li>Any other ideas?</li>
  </ul>