Golang 单元测试之路漫漫 | Go主题月

作为 Gopher 的我,除了编写业务逻辑代码外,还需要写一大堆单元测试,这占了很大一部分的工作量,足以表明它的重要性。

项目结构

我们的项目结构应该是类似下面这样的,calc.go 会对应有一个 calc_test.go 的测试用例文件:

example/
   |--calc.go
   |--calc_test.go
复制代码

让我们来看下 calc.go 文件的内容:

package example

func Add(a, b int) int {
    return a + b
}
复制代码

对应 calc_test.go 的测试用例可以是这样的:

package example

import "testing"

func TestAdd(t *testing.T) {
    if ans := Add(1, 2); ans != 3 {
        t.Errorf("1 + 2 expected be 3, but %d got", ans)
    }

    if ans := Add(-1, -2); ans != -3 {
        t.Errorf("-1 + -2 expected be -3, but %d got", ans)
    }
}
复制代码

我们可以运行 go test,这个 package 下所有的测试用例都会被执行。

go test 命令介绍

这里我们用到了 go test 命令,这个命令会自动读取源码目录下面名为 *_test.go 的文件,生成并运行测试用的可执行文件。

性能测试系统可以给出代码的性能数据,帮助测试者分析性能问题。

go test 参数说明:

  • -bench regexp 执行相应的 benchmarks,例如:-bench=.
  • -cover 可以查看覆盖率
  • -run regexp 只运行 regexp 匹配的函数,例如:-run Array 那么就执行包含有 Array 开头的函数,该参数支持通配符 *,和部分正则表达式,例如 ^$
  • -v 显示测试的详细信息

例如执行某个文件里的所有测试用例,以及使用 -v 显示详细的信息

$ go test helloworld_test.go
ok          command-line-arguments        0.003s
$ go test -v helloworld_test.go
=== RUN   TestHelloWorld
--- PASS: TestHelloWorld (0.00s)
        helloworld_test.go:8: hello world
PASS
ok          command-line-arguments        0.004s
复制代码

总结

本文简单介绍如何编写 Golang 的单元测试以及 go test 的基本用法,但 Golang 的单元测试远不如此,大家一定要保持学习!

猜你喜欢

转载自juejin.im/post/6945103902429675533