编写测试用例

因为go test命令只能在一个相应的目录下执行所有文件,所以我们接下来新建一个项目目录gotest,这样我们所有的代码和测试代码都在这个目录下。

接下来我们在该目录下面创建两个文件:test.go和gotest_test.go

test.go:这个文件里面我们是创建了一个包,里面有一个函数实现了除法运算:

  1. package gotest
  2. import (
  3. "errors"
  4. )
  5. func Division(a, b float64) (float64, error) {
  6. if b == 0 {
  7. return 0, errors.New("除数不能为0")
  8. }
  9. return a / b, nil
  10. }

go_test.go:这是我们的单元测试文件,但是记住下面的这些原则:

  • 文件名必须是_test.go结尾的,这样在执行go test的时候才会执行到相应的代码
  • 你必须import testing这个包
  • 所有的测试用例函数必须是Test开头
  • 测试用例会按照源代码中写的顺序依次执行
  • 测试函数TestXxx()的参数是testing.T,我们可以使用该类型来记录错误或者是测试状态
  • 测试格式:func TestXxx (t *testing.T),Xxx部分可以为任意的字母数字的组合,但是首字母不能是小写字母[a-z],例如Testintdiv是错误的函数名。
  • 函数中通过调用testing.TError, Errorf, FailNow, Fatal, FatalIf方法,说明测试不通过,调用Log方法用来记录测试的信息。

下面是我们的测试用例的代码:

  1. package gotest
  2. import (
  3. "testing"
  4. )
  5. func Test_Division_1(t *testing.T) {
  6. if i, e := Division(6, 2); i != 3 || e != nil { //try a unit test on function
  7. t.Error("除法函数测试没通过") // 如果不是如预期的那么就报错
  8. } else {
  9. t.Log("第一个测试通过了")
  10. }
  11. }
  12. func Test_Division_2(t *testing.T) {
  13. t.Error("error")
  14. }

我们在项目目录下面执行go test,就会显示如下信息:

—- FAIL: Test_Division_2 (0.00 seconds) go_test.go:16: error FAIL exit status 1 FAIL go 0.013s

从这个结果显示测试没有通过,因为在第二个测试函数中我们写死了测试不通过的代码t.Error,那么我们的第一个函数执行的情况怎么样呢?默认情况下执行go test是不会显示测试通过的信息的,我们需要带上参数go test -v,这样就会显示如下信息:

=== RUN Test_Division_1 —- PASS: Test_Division_1 (0.00 seconds) go_test.go:11: 第一个测试通过了 === RUN Test_Division_2 —- FAIL: Test_Division_2 (0.00 seconds) go_test.go:16: =error FAIL exit status 1 FAIL go 0.012s

上面的输出详细的展示了这个测试的过程,我们看到测试函数1Test_Division_1测试通过,而测试函数2Test_Division_2测试失败了,最后得出结论测试不通过。接下来我们把测试函数2修改成如下代码:

  1. func Test_Division_2(t *testing.T) {
  2. if _, e := Division(6, 0); e == nil { //try a unit test on function
  3. t.Error("Division did not work as expected.") // 如果不是如预期的那么就报错
  4. } else {
  5. t.Log("one test passed.", e) //记录一些你期望记录的信息
  6. }
  7. }

然后我们执行go test -v,就显示如下信息,测试通过了:

=== RUN Test_Division_1 —- PASS: Test_Division_1 (0.00 seconds) go_test.go:11: 第一个测试通过了 === RUN Test_Division_2 —- PASS: Test_Division_2 (0.00 seconds) go_test.go:20: one test passed. 除数不能为0 PASS ok go 0.013s