在Go语言中进行单元测试时,你是否觉得每次都要手动写 if 来判断结果有些繁琐?这是因为 Go 语言的标准测试库本身并未提供断言(Assert)功能。如果需要断言,我们必须手动比对实际结果与期望结果是否一致,具体示例如下:
待测程序
package main
type Number interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
~float32 | ~float64
}
func Add[T Number](a, b T) T {
return a + b
}
测试程序(使用标准库)
package main
import "testing"
func TestAddInt(t *testing.T) {
expectValue := 30
actualValue := Add(10, 20)
if actualValue != expectValue {
t.Errorf("expect value: %d ,actual value: %d\n", expectValue, actualValue)
}
}
func TestAddFloat32(t *testing.T) {
var expectValue float32 = 30.03
actualValue := Add[float32](10.01, 20.02)
if actualValue != expectValue {
t.Errorf("expect value: %f ,actual value: %f \n", expectValue, actualValue)
}
}
如果你有过其他编程语言(如 Python 的 pytest、Java 的 JUnit)的测试框架使用经验,一定会对便捷的 assert 断言方式念念不忘。为了解决这一痛点,社区涌现了多个第三方断言库。其中,目前被广泛推荐和使用的是 testify,其 GitHub 仓库地址为:https://github.com/stretchr/testify。
安装testify
在初始化好你的 Go 项目后,可以使用以下命令进行安装:
go get github.com/stretchr/testify
安装完成后,你的项目中会自动引入 testify 的几个核心模块:
github.com/stretchr/testify/assert
github.com/stretchr/testify/require
github.com/stretchr/testify/mock
github.com/stretchr/testify/suite
这些模块分别提供了断言、强制断言(失败即终止测试)、模拟对象和测试套件等功能,能够极大地提升你编写单元测试的效率和体验。后续我们将深入探讨这些功能的具体用法,帮助你在开发中构建更健壮、可维护的代码。
|