测试函数以获得100%的覆盖率。

huangapple go评论80阅读模式
英文:

Testing function to get 100% coverage

问题

你好!以下是对该函数编写测试以实现100%覆盖率的方法:

首先,你需要导入所需的测试包和函数包:

import (
    "testing"
    "os"
    "fmt"
)

然后,你可以编写一个测试函数来测试countLines函数:

func TestCountLines(t *testing.T) {
    // 创建一个测试用的文件切片
    files := []string{"file1.txt", "file2.txt"}

    // 调用countLines函数
    result := countLines(files)

    // 检查返回的结果是否符合预期
    expected := 0 // 你需要根据具体情况设置预期值
    if result != expected {
        t.Errorf("Expected %d, but got %d", expected, result)
    }
}

在测试函数中,你可以创建一个测试用的文件切片,然后调用countLines函数并将结果与预期值进行比较。如果结果与预期值不匹配,你可以使用t.Errorf函数输出错误信息。

最后,你可以在测试文件中运行该测试函数,以确保对countLines函数进行了全面的测试。

希望这可以帮助到你!如果你有任何其他问题,请随时问我。

英文:

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\n", err)
      continue
    }
    sum += countFileLine(f)
    f.Close()
  }
  return sum
}

答案1

得分: 2

极端的方式

将方法签名更改为接受 func (string) (os.File, error) 作为输入,并在进行测试时进行注入。

大致如下:

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

然后,您可以进行测试并注入一个函数,该函数将返回您为测试安排的内容。

实用的方式

只需在包的 test 目录下创建文件,并使用这些文件进行测试。
优点是方法更简单,测试也更简单。当您有很多依赖项时,第一种方法可能会变得相当麻烦...

英文:

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…

huangapple
  • 本文由 发表于 2015年12月23日 20:17:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/34435542.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定