【质量文化第三弹】经典推荐: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开发工程师的单测时发现功能场景覆盖不全的情况大有发生,于是就有了这篇单测最佳实践的宣传,期望开发工程师在编写单测时能兼顾效率和场景覆盖。


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

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

相关推荐
新world3 天前
mybatis-plus从入门到入土(二):单元测试
单元测试·log4j·mybatis
仰望星空@脚踏实地4 天前
Spring Boot Web 服务单元测试设计指南
spring boot·后端·单元测试
啃火龙果的兔子6 天前
前端单元测试覆盖率工具有哪些,分别有什么优缺点
前端·单元测试
编程乐学(Arfan开发工程师)16 天前
75、单元测试-嵌套测试
前端·javascript·redis·python·单元测试·bootstrap
编程乐学(Arfan开发工程师)16 天前
73、单元测试-断言机制
服务器·数据库·servlet·单元测试·sqlite·log4j·mybatis
编程乐学(Arfan开发工程师)16 天前
74、单元测试-前置条件
redis·python·阿里云·单元测试·云计算·bootstrap
不一样的少年_16 天前
前端单元测试的救星:Vitest 输入和 Mock 技术详解
前端·单元测试
十连满潜16 天前
springboot集成mockito和jacoco实践
后端·单元测试·mockito
bo5210019 天前
vue3单元测试-项目实战
vue.js·单元测试
bo5210020 天前
vue3单元测试-初步了解
vue.js·单元测试