找回密码
立即注册
搜索
热搜: Java Python Linux Go
发回帖 发新帖

1693

积分

0

好友

274

主题
发表于 10 小时前 | 查看: 0| 回复: 0

在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

这些模块分别提供了断言、强制断言(失败即终止测试)、模拟对象和测试套件等功能,能够极大地提升你编写单元测试的效率和体验。后续我们将深入探讨这些功能的具体用法,帮助你在开发中构建更健壮、可维护的代码。




上一篇:OBS二次开发:dshow_input插件引用计数未清零导致摄像头指示灯常亮
下一篇:DarkSpectre间谍活动曝光:恶意浏览器扩展窃取880万用户数据
您需要登录后才可以回帖 登录 | 立即注册

手机版|小黑屋|网站地图|云栈社区 ( 苏ICP备2022046150号-2 )

GMT+8, 2026-1-24 17:29 , Processed in 0.295118 second(s), 42 queries , Gzip On.

Powered by Discuz! X3.5

© 2025-2026 云栈社区.

快速回复 返回顶部 返回列表