首页 > 后端开发 > Golang > 正文

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

王林
发布: 2024-09-24 18:30:02
原创
510人浏览过

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

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

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

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

步骤:

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

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

代码示例:

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) {
            // 使用输入值进行测试
            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,它根据两点之间的坐标计算距离。您可以使用参数化测试来验证此函数。

func 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), 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 math.Sqrt(dx*dx + dy*dy)
}
登录后复制

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

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号