测试功能获得100%覆盖率

How would you write a test for the below function to get 100% coverage?

func countLines(files []string) int {
  sum := 0
  for _, e := range files {
    f, err := os.Open(e)
    if err != nil {
      fmt.Fprintf(os.Stderr, "err: %v
", err)
      continue
    }
    sum += countFileLine(f)
    f.Close()
  }
  return sum
}

The extremist way

Change the method signature to take as input a func (string) (os.File, error) and inject it while doing the tests.

Something along these lines:

func countLines(files []string, open func(string) (*os.File, error)) int {
    ...
    f, err := open(e)
    ...
}

Then, you can do tests and inject a function that will returns what arrange you for the test.

The practical way

Simply create files under a test directory of your packages, and do you tests using these files. The upside is that the method is simpler, the tests too. The first method can become quite bothersome when you have a lot of dependencies…