dongyou4411 2015-12-23 12:17
浏览 153
已采纳

测试功能获得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
}
  • 写回答

1条回答 默认 最新

  • dongyi9082 2015-12-23 12:54
    关注

    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…

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?