Go 中 assert 使用
前言
在本周的服务计算作业中,我发现老师写的测试文件使用了 assert 函数代替了之前的 Errorf,这是我第一次看到这个函数,并且发现该函数用于测试文件十分方便,于是在此记录。
asset 包的获取
使用以下命令就可以获取 asset 程序包
go get github.com/stretchr/testify/assert
使用完此命令后可以在本地的 GOPATH/src 路径下发现多了三个文件夹:davecgh、stretchr、pmezard ,即为获取成功
新旧测试文件对比
以一个简单的整数相加的函数为例,分别写两个测试文件
func add(a, b int) int {
return a + b
}
普通的测试文件:
func TestWithoutAssert(t *testing.T) {
if add(1, 3) != 4 {
t.Error("add(1+3) ne 4")
}
// this will raise an error
if add(1, 3) != 5 {
t.Error("add(1+3) ne 5")
}
}
这样是可以完成测试的,但是看起来代码就比较乱,不简洁
这时就可以调用 assert 程序包中的函数简单的进行测试
func TestWithAssert(t *testing.T) {
assert.Equal(t, add(1, 2), 3, "Add Error!")
// this will raise an error
assert.Equal(t, add(1, 3), 5, "Add Error!")
}
这样在测试工程量很大的项目时,测试文件会显得比较简介,方便检查
在官方的 API 文件中也有一个例子,将此程序包的用法进行了介绍:
The following is a complete example using assert in a standard test function:
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestSomething(t *testing.T) {
var a string = "Hello"
var b string = "Hello"
assert.Equal(t, a, b, "The two words should be the same.")
}
if you assert many times, use the format below:
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestSomething(t *testing.T) {
assert := assert.New(t)
var a string = "Hello"
var b string = "Hello"
assert.Equal(a, b, "The two words should be the same.")
断言允许您轻松地编写测试代码,并且是“assert”包中的全局函数。所有断言函数都将测试框架提供的*testing.T对象作为第一个参数。这允许断言函数将失败和其他详细信息写入正确的位置。
每个断言函数还将可选的字符串消息作为最终参数,允许将自定义错误消息附加到断言方法输出的消息中。
本文介绍了Go语言中assert的使用,通过对比传统的测试文件,展示了assert如何使测试代码更加简洁。首先,讲解了如何获取assert包,然后通过一个整数相加函数的例子,演示了使用assert进行测试的方法,最后引用了官方API的一个例子,进一步阐述了assert在测试中的应用。
1763

被折叠的 条评论
为什么被折叠?



