当前位置: 首页 > news >正文

Go Convey测试框架入门(go convey gomonkey)

Go Convey测试框架入门

介绍

GoConvey是一款针对Golang的测试框架,可以管理和运行测试用例,同时提供了丰富的断言函数,并支持很多 Web 界面特性。
Golang虽然自带了单元测试功能,并且在GoConvey框架诞生之前也出现了许多第三方测试框架,但没有一个测试框架像GoConvey一样能够让程序员如此简洁优雅的编写测试代码。

官网:http://smartystreets.github.io/goconvey/

安装

go get 方式安装(go path时代,关闭go mod)

//下载源码并执行go build
//源码下载到$GOPATH/src目录
//go build之后的结果到$GOPATH/bin
go get github.com/smartystreets/goconvey

在$GOPATH/src目录下新增了github.com子目录,该子目录里包含了GoConvey框架的库代码 在$GOPATH/bin目录下新增了GoConvey框架的可执行程序goconvey

go install方式(开启go mod)

在gomod时代一般不需要先显式安装(gomod机制会自动从goproxy拉取依赖到本地cache),只需要go.mod中引入,然后go mod tidy即可。除非要使用GoConvey的web界面,这时需要提前安装GoConvey的二进制,命令为go install github.com/smartystreets/goconvey@latest。

go.mod:

module ziyi.convey.comgo 1.19require github.com/smartystreets/goconvey v1.8.1require (github.com/gopherjs/gopherjs v1.17.2 // indirectgithub.com/jtolds/gls v4.20.0+incompatible // indirectgithub.com/smarty/assertions v1.15.0 // indirect
)
//我后面要演示web页面,因此这里显示安装一下
//安装之后,依然会将编译好的二进制放在$GOPATH/bin
go install github.com/smartystreets/goconvey@latest

我的GOPATH为E:\Go\GoPro:
在这里插入图片描述

使用

注意事项

  1. import goconvey包时,前面加点号".",以减少冗余的代码。凡是在测试代码中看到Convey和So两个方法,肯定是convey包的。我们需要注意不要在产品代码中定义相同的函数名
  2. 测试函数的名字必须以Test开头,而且参数类型必须为*testing.T
  3. 每个测试用例必须使用Convey函数包裹起来,它的第一个参数为string类型的测试描述,第二个参数为测试函数的入参(类型为*testing.T),第三个参数为不接收任何参数也不返回任何值的函数(习惯使用闭包)
  4. Convey函数的第三个参数闭包的实现中通过So函数完成断言判断,它的第一个参数为实际值,第二个参数为断言函数变量,第三个参数或者没有(当第二个参数为类ShouldBeTrue形式的函数变量)或者有(当第二个函数为类ShouldEqual形式的函数变量)

案例一:1个测试用例1个Convey

c_test.go:

package mainimport (. "github.com/smartystreets/goconvey/convey""testing"
)func TestEqualWithSingleTestCase(t *testing.T) {// test name:用例名称// t:需要传入*testing.T// func(){} 测试函数Convey("test name", t, func() {//1+1:断言//ShouldEqual:convey内置的断言//2:期望结果So(1+1, ShouldEqual, 2)})
}

在这里插入图片描述

案例二:多个Convey多个测试用例

①平铺写法

func TestEqualWithMultipleTestCase(t *testing.T) {Convey("test add case", t, func() {So(1+1, ShouldEqual, 2)})Convey("test sub case", t, func() {So(1-1, ShouldEqual, 0)})Convey("test multi case", t, func() {So(1*1, ShouldNotEqual, -1)})
}

②Convey嵌套写法

只需要最外层的Convey传t *testing.T即可

func TestEqualWithMultipleTestCaseAndNested(t *testing.T) {Convey("test case", t, func() {Convey("test add case", func() {So(1+1, ShouldEqual, 2)})Convey("test sub case", func() {So(1-1, ShouldEqual, 0)})Convey("test multi case", func() {So(1*1, ShouldNotEqual, -1)})})
}

案例三:"函数式"断言(assert传入函数)

// 案例三:函数式断言
func TestFunctionalAssertion(t *testing.T) {Convey("test case", t, func() {So(add(1, 1), ShouldEqual, 2)})
}func add(a, b int) int {return a + b
}

案例四:忽略部分Convey断言

针对想忽略但又不想删掉或注释掉某些断言操作,GoConvey提供了Convey/So的Skip方法:

  • SkipConvey函数表明相应的闭包函数将不被执行
  • SkipSo函数表明相应的断言将不被执行

当存在SkipConvey或SkipSo时,测试日志中会显式打上"skipped"形式的标记:

当测试代码中存在SkipConvey时,相应闭包函数中不管是否为SkipSo,都将被忽略。
不管存在SkipConvey还是SkipSo时,测试日志中都有字符串"{n} total assertions (one or more sections skipped)",其中{n}表示测试中实际已运行的断言语句数

// 案例四:忽略Convey断言
//忽略所有断言
func TestCaseSkipConvey(t *testing.T) {SkipConvey("test case", t, func() {So(add(1, 1), ShouldEqual, 2)})
}//忽略某些断言(SkipSo的断言将被忽略)
func TestCaseSkipSo(t *testing.T) {Convey("test case", t, func() {SkipSo(add(1, 1), ShouldEqual, 2)So(1-1, ShouldEqual, 0)})
}

比如我执行TestCaseSkipSo函数:
在这里插入图片描述

案例五:定制断言函数

①原理分析

  1. 查看So源码
func So(actual interface{}, assert Assertion, expected ...any)

在这里插入图片描述
2. 点击查看Assertion结构体

type Assertion func(actual any, expected ...any) string

当Assertion的变量的返回值为""时表示断言成功,否则表示失败:

const assertionSuccess = ""

在这里插入图片描述
3. 结论
因此我们只需要按照结构,实现func,最后返回空串代表断言成功,否则失败

②实际操作

从上面的分析我们可以知道,当Assertion最后返回""代表断言成功,反之失败

// 案例五:定制断言
func TestCustomAssertion(t *testing.T) {Convey("test custom assert", t, func() {So(1+1, CustomAssertionWithRaiseMoney, 2)})
}func CustomAssertionWithRaiseMoney(actual any, expected ...any) string {if actual == expected[0] {return ""} else {return "doesn't raise money"}
}

案例六:访问web页面

如果要访问web页面,需要有goconvey.exe程序并运行,同时需要将xxx_test.go文件放在与exe同目录,否则无法识别到

  • go get “github.com/smartystreets/goconvey”
  • go install “github.com/smartystreets/goconvey” (如果开启了go mod,则用该方式)

默认安装到$GOPATH/bin目录下

执行exe后,访问本地localhost:8080端口即可看到web页面,页面展示的了单测的通过情况等。
在这里插入图片描述

拓展:gomonkey(打桩工具)

如果在被测函数中调用了其他函数(比如其他业务方的),可以使用以下方法,gomonkey打桩工具

  • 官网:https://github.com/agiledragon/gomonkey
//安装依赖
go get "github.com/agiledragon/gomonkey"

给全局变量打桩

使用 gomonkey 可以方便地模拟函数的行为


// 拓展:配合monkey打桩
var num = 10 //全局变量func TestApplyGlobalVar(t *testing.T) {Convey("TestApplyGlobalVar", t, func() {Convey("change", func() {//模拟函数行为,给全局变量复制,在函数结束后直接通过reset恢复全局变量值patches := gomonkey.ApplyGlobalVar(&num, 150)defer patches.Reset()So(num, ShouldEqual, 150)})Convey("recover", func() {So(num, ShouldEqual, 10)})})
}

给函数打桩

//对函数进行打桩
func TestFunc(t *testing.T) {// mock 了 networkCompute(),返回了计算结果2patches := gomonkey.ApplyFunc(networkCompute, func(a, b int) (int, error) {return 2, nil})defer patches.Reset()sum, err := Compute(1, 2)println("expected %v, got %v", 2, sum)if sum != 2 || err != nil {t.Errorf("expected %v, got %v", 2, sum)}
}func networkCompute(a, b int) (int, error) {// do something in remote computerc := a + breturn c, nil
}func Compute(a, b int) (int, error) {sum, err := networkCompute(a, b)return sum, err
}

全部代码:

欢迎大家star在这里插入图片描述

  • Github:https://github.com/ziyifast/ziyifast-code_instruction/tree/main/go-demo/go-convey
    在这里插入图片描述

c_test.go:

package mainimport ("github.com/agiledragon/gomonkey"_ "github.com/agiledragon/gomonkey". "github.com/smartystreets/goconvey/convey""testing"
)// 案例一:一个Convey,一个用例
func TestEqualWithSingleTestCase(t *testing.T) {// test name:用例名称// t:需要传入*testing.T// func(){} 测试函数Convey("test name", t, func() {//1+1:断言//ShouldEqual:convey内置的断言//2:期望结果So(1+1, ShouldEqual, 2)})
}// 案例二:多个Convey,多个用例(平铺写法)
func TestEqualWithMultipleTestCase(t *testing.T) {Convey("test add case", t, func() {So(1+1, ShouldEqual, 2)})Convey("test sub case", t, func() {So(1-1, ShouldEqual, 0)})Convey("test multi case", t, func() {So(1*1, ShouldNotEqual, -1)})
}// 案例二:多个Convey,多个用例(嵌套写法)
func TestEqualWithMultipleTestCaseAndNested(t *testing.T) {Convey("test case", t, func() {Convey("test add case", func() {So(1+1, ShouldEqual, 2)})Convey("test sub case", func() {So(1-1, ShouldEqual, 0)})Convey("test multi case", func() {So(1*1, ShouldNotEqual, -1)})})
}// 案例三:函数式断言
func TestFunctionalAssertion(t *testing.T) {Convey("test case", t, func() {So(add(1, 1), ShouldEqual, 2)})
}func add(a, b int) int {return a + b
}// 案例四:忽略Convey断言
// 忽略所有断言
func TestCaseSkipConvey(t *testing.T) {SkipConvey("test case", t, func() {So(add(1, 1), ShouldEqual, 2)})
}// 忽略某些断言(SkipSo的断言将被忽略)
func TestCaseSkipSo(t *testing.T) {Convey("test case", t, func() {SkipSo(add(1, 1), ShouldEqual, 2)So(1-1, ShouldEqual, 0)})
}// 案例五:定制断言
func TestCustomAssertion(t *testing.T) {Convey("test custom assert", t, func() {So(1+1, CustomAssertionWithRaiseMoney, 2)})
}func CustomAssertionWithRaiseMoney(actual any, expected ...any) string {if actual == expected[0] {return ""} else {return "doesn't raise money"}
}// 拓展:配合monkey打桩
var num = 10 //全局变量func TestApplyGlobalVar(t *testing.T) {Convey("TestApplyGlobalVar", t, func() {Convey("change", func() {//模拟函数行为,给全局变量复制,在函数结束后直接通过reset恢复全局变量值patches := gomonkey.ApplyGlobalVar(&num, 150)defer patches.Reset()So(num, ShouldEqual, 150)})Convey("recover", func() {So(num, ShouldEqual, 10)})})
}// 对函数进行打桩
func TestFunc(t *testing.T) {// mock 了 networkCompute(),返回了计算结果2patches := gomonkey.ApplyFunc(networkCompute, func(a, b int) (int, error) {return 2, nil})defer patches.Reset()sum, err := Compute(1, 2)println("expected %v, got %v", 2, sum)if sum != 2 || err != nil {t.Errorf("expected %v, got %v", 2, sum)}
}func networkCompute(a, b int) (int, error) {// do something in remote computerc := a + breturn c, nil
}func Compute(a, b int) (int, error) {sum, err := networkCompute(a, b)return sum, err
}

go.mod:

module ziyi.convey.comgo 1.19require (github.com/agiledragon/gomonkey v2.0.2+incompatiblegithub.com/smartystreets/goconvey v1.8.1
)require (github.com/gopherjs/gopherjs v1.17.2 // indirectgithub.com/jtolds/gls v4.20.0+incompatible // indirectgithub.com/smarty/assertions v1.15.0 // indirect
)

参考文章:
http://smartystreets.github.io/goconvey/
https://www.jianshu.com/p/e3b2b1194830

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 特殊类设计和类型转换
  • 进阶SpringBoot之 SpringSecurity(2)用户认证和授权
  • TIM输出比较之PWM驱动直流电机应用案例
  • UEFI启动流程
  • 《黑神话:悟空》到底是用什么语言开发的
  • 从0到1构建视频汇聚生态:EasyCVR视频汇聚平台流媒体协议支持的前瞻性布局
  • 依靠 VPN 生存——探索 VPN 后利用技术
  • 【Python】列表和元组
  • 两个独立的SpringBoot项目如何互相引用?
  • 20240824给飞凌OK3588-C的核心板刷Ubuntu22.04后适配SONY索尼的HDMI OUT的机芯8530
  • 【通俗易懂】限流、降级、熔断有什么区别?
  • C语言刷题日记(附详解)(2)
  • 防患未然:构建AIGC时代下开发团队应对突发技术故障与危机的全面策略
  • 代码随想录算法训练营day30 | 贪心算法 | 452.用最少数量的箭引爆气球、435.无重叠区间、763.划分字母区间
  • PostgreSQL SELECT 语句:深入解析与实例应用
  • JavaScript-如何实现克隆(clone)函数
  • [rust! #004] [译] Rust 的内置 Traits, 使用场景, 方式, 和原因
  • 【干货分享】SpringCloud微服务架构分布式组件如何共享session对象
  • ➹使用webpack配置多页面应用(MPA)
  • 2018天猫双11|这就是阿里云!不止有新技术,更有温暖的社会力量
  • css选择器
  • extjs4学习之配置
  • JWT究竟是什么呢?
  • Spring思维导图,让Spring不再难懂(mvc篇)
  • 紧急通知:《观止-微软》请在经管柜购买!
  • 每天一个设计模式之命令模式
  • 我建了一个叫Hello World的项目
  • 走向全栈之MongoDB的使用
  • 【云吞铺子】性能抖动剖析(二)
  • # 职场生活之道:善于团结
  • #《AI中文版》V3 第 1 章 概述
  • ()、[]、{}、(())、[[]]命令替换
  • (NO.00004)iOS实现打砖块游戏(十二):伸缩自如,我是如意金箍棒(上)!
  • (二)丶RabbitMQ的六大核心
  • (附源码)计算机毕业设计SSM疫情下的学生出入管理系统
  • (三)Kafka 监控之 Streams 监控(Streams Monitoring)和其他
  • (生成器)yield与(迭代器)generator
  • (源码版)2024美国大学生数学建模E题财产保险的可持续模型详解思路+具体代码季节性时序预测SARIMA天气预测建模
  • (转) ns2/nam与nam实现相关的文件
  • (转)创业的注意事项
  • (轉)JSON.stringify 语法实例讲解
  • ***原理与防范
  • .bat批处理(九):替换带有等号=的字符串的子串
  • .MSSQLSERVER 导入导出 命令集--堪称经典,值得借鉴!
  • .NET Framework与.NET Framework SDK有什么不同?
  • .NET开源的一个小而快并且功能强大的 Windows 动态桌面软件 - DreamScene2
  • [2019.2.28]BZOJ4033 [HAOI2015]树上染色
  • [BJDCTF 2020]easy_md5
  • [CDOJ 1343] 卿学姐失恋了
  • [CentOs7]图形界面
  • [codevs 1288] 埃及分数 [IDdfs 迭代加深搜索 ]
  • [EFI]ASUS Vivobook 16x M1603QA 电脑 Hackintosh 黑苹果efi引导文件
  • [hdu 3652] B-number
  • [JavaWeb]——过滤器filter与拦截器Interceptor的使用、执行过程、区别
  • [leveldb] 2.open操作介绍