ZVVQ代理分享网

在 golang 框架中进行单元测试时应遵循哪些设计准

作者:zvvq博客网
导读go 框架中单元测试设计准则:1. 单元测试应专注于一个函数;2. 使用表驱动的测试;3. 对副作用进行模拟;4. 编写可读且可维护的测试;5. 使用覆盖率工具。实战案例:测试一个查找

go 框架中单元测试设计准则:1. 单元测试应致力于一个函数;2. 应用表驱动检测;3. 对副作用进行模拟;4. 撰写可读并可维修的检测;5. 应用普及率工具。实战案例 :检测一个查找字符串数组中最高值的函数,同时符合规则。

在 Go 框架中开展单元测试的设计准则

1. 单元测试应粒度小且专注

单元测试应只检测一个实际函数或方法。这将使检测易于维护和调试。

2. 应用表驱动检测

表驱动检测允许您给予一组键入和预期导出,并对每个键入运行测试。这有利于捕捉边沿状况并简化检测维护。

import (

"testing"

"reflect"

)

func TestAdd(t testing.T) {

tests := []struct {

input1, input2 int

expected int

}{

{1, 2, 3},

{3, 4, 7},

{-1, -2, -3},

}

for _, test := range tests {

actual := Add(test.input1, test.input2)

if actual != test.expected {

t.Errorf("Add(%d, %d): expected %d, got %d", test.input1, test.input2, test.expected, actual)

}

}

}

3. 对副作用进行模拟

单元测试应不同于外在因素,比如数据库或网络启用。应用模拟或存根来防护这种依赖项,以保证检测准确可靠。

4. 撰写可读并可维修的检测

检测应清晰易懂,便于别的开发者能够轻松认知和维护。应用有价值的变量和函数名称,并撰写注解以解释检测的用意。

5. 应用普及率工具

普及率工具能够帮助你考量检测对代码库的覆盖水平。这可以识别未涵盖的编码途径,并促使您撰写更专业的检测。

实战案例 :检测一个简单的函数

考虑下列函数,用以查找字符串数组中的最大值:

func Max(arr []string) string {

if len(arr) == 0 {

return ""

}

max := arr[0]

for _, s := range arr {

if s > max {

max = s

}

}

return max

}

我们可以使用下列单元测试来检测此函数:

import (

"testing"

"reflect"

"strings"

)

func TestMax(t testing.T) {

tests := []struct {

input []string

expected string

}{

{[]string{"a", "b", "c"}, "c"},

{[]string{"z", "y", "x"}, "z"},

{[]string{"1", "2", "3"}, "3"},

{[]string{}, ""},

}

for _, test := range tests {

actual := Max(test.input)

if actual != test.expected {

t.Errorf("Max(%s): expected %s, got %s", strings.Join(test.input, ", "), test.expected, actual)

}

}

}

这个测试同时符合设计准则:

它检测单独函数(Max)它使用表推动检测来包含各种键入它使用模拟来防护对输入数组的依赖项它清楚易懂以上就是在golang框架中开展单元测试时要遵循什么设计准则?的详细内容,大量请关注其他类似文章!