【质量文化第三弹】经典推荐:Table-Driven Unit Tests

在软件开发领域,有个DRY原则:Don't Repeat Yourself。注重简单高效的 Go提供了Table-Driven Unit Tests的编程模式,使用表格式在单个测试函数中定义多个输入和预期输出组合,而不是编写单个测试用例。通过这种方式,开发人员可以测试各种场景和边缘情况,并将代码重复率降到最低。本篇旨在通过示例分享Table-Driven Unit Tests写法,并与单个用例写法进行对比,让大家在写单测时能够选择更优方式。

table-Driven写法
go 复制代码
func TestRegexps(t *testing.T) {
	re := regexp.MustCompile(`text`)
	cases := map[string]struct { //注:这里的cases定义的结构是map[string]struct,好处是1.若case占用屏幕过长,可以折叠;2.执行时可以暴露具体失败的位置
		give     string
		expected bool
	}{
		"plus-signs":           {"+text+", true},
		"multiline-plus-signs": {"+text\nline2\nline3+", true},
		"money":                {"$text$", true},
		"multiline-money":      {"$text\nmulutple\nline$", true},
		"quotes":               {"pass:quotes[text]", true},
		"multiline-quotes":     {"pass:quotes[text\nline2\nline3]", true},
	}

	for name, tc := range cases {
		t.Run(name, func(t *testing.T) {
			result := re.MatchString(tc.give)
			assert.Equal(t, tc.expected, result)
		})
	}
}

若是case执行失败,可以看到具体失败的位置,如下:

当失败case修复完后 ,也可以指定某个具体case重跑,如go test -run="TestRegexps/money"

非table-driven写法
go 复制代码
func TestRegexps(t *testing.T) {
   re := regexp.MustCompile(`text`)
   Convey("Given the regexp `text`", t, func() {
      Convey("When testing various cases", func() {
         give := "+text+"
         expected := true
         result := re.MatchString(give)
         Convey("It should match for plus signs", func() {
            So(result, ShouldEqual, expected)
         })
         give = "+text\nline2\nline3+"
         expected = true
         result = re.MatchString(give)
         Convey("It should match for multiline plus signs", func() {
            So(result, ShouldEqual, expected)
         })
         give = "$text$"
         expected = true
         result = re.MatchString(give)
         Convey("It should match for money signs", func() {
            So(result, ShouldEqual, expected)
         })
         give = "$text\nmulutple\nline$"
         expected = true
         result = re.MatchString(give)
         Convey("It should match for multiline money signs", func() {
            So(result, ShouldEqual, expected)
         })
         give = `pass:quotes[text]`
         expected = true
         result = re.MatchString(give)
         Convey("It should match for quotes", func() {
            So(result, ShouldEqual, expected)
         })
         give = "pass:quotes[text\nline2\nline3]"
         expected = true
         result = re.MatchString(give)
         Convey("It should match for multiline quotes", func() {
            So(result, ShouldEqual, expected)
         })
      })
   })
}

如上对比,可以看出非Table-driven方式写起来篇幅更长,且比较容易遗漏导致场景覆盖不全。

Table-Driven Unit Tests优势

简洁易维护: Table-Driven Unit Tests将测试用例定义和测试执行逻辑明确分开,有助于消除冗余代码,使测试代码更易于维护。

可扩展性: 随着代码库的增长,测试用例的数量也会增加,通过Table-Driven Unit Tests,可以轻松扩展。

覆盖范围:Table-Driven Unit Tests可确保全面覆盖不同的输入组合,这种方法有助于识别可能遗漏的边缘场景。

Table-Driven Unit Tests一些不适用场景

如果测试用例涉及复杂的设置、交互和依赖关系,或需要不同的预置条件,或需要自定义断言等,使用Table-Driven 写起来可能并不便利。

并且虽然Table-Driven能促进代码重用和简化,但是当table变得庞大复杂时,会降低测试代码的可读性和清晰度,违反测试代码的DAMP(Descriptive and Meaningful Phrases)原则。

总结

以上是我在公司宣传的单测系列的第三期内容,背景是在review开发工程师的单测时发现功能场景覆盖不全的情况大有发生,于是就有了这篇单测最佳实践的宣传,期望开发工程师在编写单测时能兼顾效率和场景覆盖。


后续的每一期内容我都会及时发布在掘金的工程师质量文化专栏,欢迎大家关注,共同进步。

最后,照例给大家看下我们在公司张贴的海报吧~

相关推荐
我命由我123453 小时前
SQL 检测脚本
java·数据库·sql·功能测试·单元测试·压力测试·可用性测试
神一样的老师3 天前
WS63 嵌入式 SSD1306 OLED 驱动单元测试实战
单元测试·log4j
CesareCheung3 天前
高级软件测试工程师面试锦集
面试·单元测试·压力测试
2501_915918414 天前
在 Xcode 中运行和调试单元测试的完整指南
ide·vscode·macos·ios·单元测试·个人开发·xcode
极小狐5 天前
MR 里测试摘要空白、覆盖率不显示?JUnit 与覆盖率配置 9 步排查
数据库·ci/cd·junit·单元测试·mr·devops·代码覆盖率
toooooop85 天前
FastAdmin(ThinkPHP 5.0)单元测试实践:从零到跑通
单元测试·fastadmin
silvamux_5 天前
大模型 API 单元测试怎么 mock 不误伤
单元测试·log4j·php
Helix2505 天前
Python单元测试实战:pytest框架从入门到企业级测试体系搭建指南
python·单元测试·实战·mock·pytest·测试覆盖率·fixture
2302_805771077 天前
Day24:DDT+EXCEL数据驱动
功能测试·单元测试·自动化·测试用例·需求分析·web自动化
孟陬7 天前
不用盲调性能参数 Vitest 5.0 新推出 `vitest doctor` 一键诊断测试慢卡点,自动给出最优提速配置
性能优化·单元测试·vite