如何在 Golang 中编写参数化的测试函数?

golang 中可以通过以下步骤编写参数化的测试函数:定义一个测试函数并使用 t.run 创建参数化测试用例。使用 t.run 的第二个参数指定输入值。在测试函数中,使用输入值进行测试。

如何在 Golang 中编写参数化的测试函数?

参数化测试函数允许您使用不同的输入值运行相同的测试,从而简化测试代码和提高覆盖率。在 Golang 中,可以使用 testing 包实现参数化测试。

步骤:

立即学习go语言免费学习笔记(深入)”;

定义一个测试函数,并使用 t.Run 创建一个测试用例。 使用 t.Run 的第二个参数指定输入值。 在测试函数中,使用输入值进行测试。

代码示项目搭建网点我wcqh.cn例:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

import (

“testing”

)

// 定义一个测试函数

func TestMyFunction(t *testing.T) {

// 使用 t.Run 创建参数化测试用例

tests := []struct {

input    int

expected int

}{

{1, 1},

{2, 4},

{3, 9},

}

for _, tt := range tests {

t.Run(fmt.Sprintf(“input:%v”, tt.input), func(t *testing.T) {

// 使用输项目搭建网点我wcqh.cn入值进行测试

result := myFunction(tt.input)

if result != tt.expected {

t.Errorf(“expected %v, got %v”, tt.expected, result)

}

})

}

}

// 待测试的函数

func myFunction(input int) int {

return input * input

}

登录后复制

实战案例:

假设您有一个函数 calculateDistance,它根据两点之间的坐标计算距离。您可以使用参数化测试来验证此函数。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

f项目搭建网点我wcqh.cnunc TestCalculateDistance(t *testing.T) {

tests := []struct {

pt1, pt2  Point

expected float64

}{

{Point{0, 0}, Point{1, 1}, 1.4142135623730951},

{Point{-2, 3}, Point{-4, 9}, 8.06225774829855},

{Point{5, -1}, Point{1, -3}, 5.0},

}

for _, tt := range tests {

t.Run(fmt.Sprintf(“input: (%v, %v)”, tt.pt1, tt.pt2)项目搭建网点我wcqh.cn, func(t *testing.T) {

result := calculateDistance(tt.pt1, tt.pt2)

if math.Abs(result-tt.expected) > 0.00001 {

t.Errorf(“expected %v, got %v”, tt.expected, result)

}

})

}

}

type Point struct {

x, y int

}

func calculateDistance(p1, p2 Point) float64 {

dx := float64(p1.x – p2.x)

dy := float64(p1.y – p2.y)

return ma项目搭建网点我wcqh.cnth.Sqrt(dx*dx + dy*dy)

}

登录后复制

以上就是如何在 Golang 中编写参数化的测试函数?的详细内容,更多请关注青狐资源网其它相关文章!

© 版权声明
THE END
喜欢就支持一下吧
点赞997 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容