Golang 单元测试

想要测试Go代码需要依赖go test命令,需注意如下事项

  • 在包目录内所有测试文件必须以_test.go结尾,go build不会把这些测试文件编译到最终的可执行文件中。
  • _test.go文件中,单元测试函数的名字须以TestXxxx的形式
  • 每个单元测试函数的参数必须为*testing.T,参数t用于报告测试是否失败以及日志信息。
func TestAdd(t *testing.T) {}
func TestSum(t *testing.T) {}

testing.T参数的拥有的方法如下:

func (c *T) Error(args ...interface{})
func (c *T) Errorf(format string, args ...interface{})
func (c *T) Fail()
func (c *T) FailNow()
func (c *T) Failed() bool
func (c *T) Fatal(args ...interface{})
func (c *T) Fatalf(format string, args ...interface{})
func (c *T) Log(args ...interface{})
func (c *T) Logf(format string, args ...interface{})
func (c *T) Name() string
func (t *T) Parallel()
func (t *T) Run(name string, f func(t *T)) bool
func (c *T) Skip(args ...interface{})
func (c *T) SkipNow()
func (c *T) Skipf(format string, args ...interface{})
func (c *T) Skipped() bool

go test 参数

  • -bench regexp 执行相应的 benchmarks,例如 -bench= (基准测试)
  • -cover 开启测试覆盖率
  • -run regexp 只运行 regexp 匹配的函数,例如 -run=Array 那么就执行包含有 Array 开头的函数;
  • -v 显示测试的详细命令

Hello案例

hello.go文件

package hello

import "fmt"

func Hello() string {
	return "Hello, world"
}

hello_test.go文件

package hello

import "testing"

func TestHello(t *testing.T) {
	got := Hello()
	want := "Hello, world"

	if got != want {
		t.Errorf("got %q want %q", got, want)
	}
}
go test -v
=== RUN   TestHello
--- PASS: TestHello (0.00s)
PASS
ok      project/Go-Note/test/hello      3.481s

测试覆盖率

测试覆盖率是你的代码被测试套件覆盖的百分比,通常我们使用的都是语句的覆盖率,也就是在测试中至少被运行一次的代码占总代码的比例。Go提供内置功能来检查你的代码覆盖率。我们可以使用**go test -cover**

案例

hello.go

package hello

import "fmt"

func Hello() string {
	return "Hello, world"
}

func Add(a, b int) int {
	return a + b
}

func PrintInfo() string {
	return fmt.Sprintf("hello and this is a test\n")
}

hello_test.go

package hello

import "testing"

func TestHello(t *testing.T) {
	got := Hello()
	want := "Hello, world"

	if got != want {
		t.Errorf("got %q want %q", got, want)
	}
}

func TestAdd(t *testing.T) {
	sum := Add(5, 5)
	if sum == 10 {
		t.Log("the result is ok")
	} else {
		t.Fatal("the result is wrong")
	}
}
PS D:\syz\study\computer_science\Go\workspaces\src\project\Go-Note\test\hello> go test -v --cover  
=== RUN   TestHello
--- PASS: TestHello (0.00s)
=== RUN   TestAdd
--- PASS: TestAdd (0.00s)
    hello_test.go:17: the result is ok
PASS
coverage: 66.7% of statements
ok      project/Go-Note/test/hello      0.289s

因为hello_test.go文件并没有测试PrintInfo()函数的代码,所以只覆盖了三分之二。

参考

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值