跳到主要内容

单元测试

一 单元测试

1.1 单元测试简介

单元测试用来检测某个模块、某个函数的执行结果是否正确,也因此能够实现监控代码质量。

Go语言中自带有一个轻量级的测试框架 testing,同时也自带了 go test 命令,可以通过这些工具来实现单元测试和性能测试。

1.2 testing的使用

go自带的testing单元测试框架使用要求:

  • 测试代码必须放在以_test.go结尾的文件中
  • 测试函数以Test为名称前缀
  • 命令go test会忽略以 _.开头的测试文件
  • 命令go build/install等正常编译操作会忽略测试文件

1.3 案例

文件目录: ![] (../images/09-01.png)

源码文件:/hello/hello.go

package hello

import "fmt"

func Hello() string{
return "world"
}

单元测试文件:/test/hello_test.go

package test

import (
"TestGo/hello"
"testing"
)

func Test_hello(t *testing.T){
r := hello.Hello()
if r != "world" {
t.FailNow()
}
}

运行测试文件:没有main方法也可以执行

go test -v test/hello_test.go 							# -v用于显示详细测试流程
go test -v -run Test_hello test/hello_test.go # 只执行Test_hello

1.4 测试中一些函数的区别

  • Fail,Error:若测试失败,则测试会继续执行
  • FailNow,Fatal:若测试失败,则测试会终止

二 代码覆盖率

代码覆盖率命令:

go test -v -cover

三 断言库

使用一些第三方的断言库也可以达到原生的单元测试效果:

import "github.com/stretchr/testify/assert"
func Test_hello(t *testing.T){
r := hello.Hello()
assert.Equal("world")
}

四 BDD测试框架

常用的BDD测试框架是:https://github.com/smartystreets/goconvey