卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章35337本站已运行395

在 golang 中为泛型函数编写单元测试

在 golang 中为泛型函数编写单元测试

php小编香蕉为您带来了一篇关于在Golang中为泛型函数编写单元测试的文章。Golang是一种强类型的编程语言,然而,它在泛型方面的支持却相对较弱。因此,为泛型函数编写单元测试可能会有一些挑战。本文将向您介绍如何在Golang中有效地为泛型函数编写单元测试,以确保代码的质量和可靠性。无论您是初学者还是有经验的开发者,本文都将为您提供实用的技巧和方法,帮助您轻松应对泛型函数的单元测试。让我们一起来看看吧!

问题内容

我有这个简单的通用函数,可以从 map 检索密钥

// getmapkeys returns the keys of a map
func getmapkeys[t comparable, u any](m map[t]u) []t {
    keys := make([]t, len(m))
    i := 0
    for k := range m {
        keys[i] = k
        i++
    }
    return keys
}

我正在尝试为其编写表驱动的单元测试,如下所示:

var testunitgetmapkeys = []struct {
    name     string
    inputmap interface{}
    expected interface{}
}{
    {
        name:     "string keys",
        inputmap: map[string]int{"foo": 1, "bar": 2, "baz": 3},
        expected: []string{"foo", "bar", "baz"},
    },
    {
        name:     "int keys",
        inputmap: map[int]string{1: "foo", 2: "bar", 3: "baz"},
        expected: []int{1, 2, 3},
    },
    {
        name:     "float64 keys",
        inputmap: map[float64]bool{1.0: true, 2.5: false, 3.1415: true},
        expected: []float64{1.0, 2.5, 3.1415},
    },
}

但是,以下代码失败

func (us *unitutilsuite) testunitgetmapkeys() {
    for i := range testunitgetmapkeys {
        us.t().run(testunitgetmapkeys[i].name, func(t *testing.t) {
            gotkeys := getmapkeys(testunitgetmapkeys[i].inputmap)
        })
    }
}


type interface{} of testunitgetmapkeys[i].inputmap does not match map[t]u (cannot infer t and u)

这已通过显式转换修复

gotKeys := getMapKeys(testUnitGetMapKeys[i].inputMap.(map[string]string))

有没有办法自动化这些测试,而不必为每个输入测试变量执行显式转换?

解决方法

请注意,除非您的泛型函数除了泛型逻辑之外还执行一些特定于类型的逻辑,否则通过针对不同类型测试该函数您将一无所获。该函数的通用逻辑对于类型参数的类型集中的所有类型都是相同的,因此可以使用单个类型完全执行。

但是如果您想针对不同类型运行测试,您可以简单地执行以下操作:

var testUnitGetMapKeys = []struct {
    name string
    got  any
    want any
}{
    {
        name: "string keys",
        got:  getMapKeys(map[string]int{"foo": 1, "bar": 2, "baz": 3}),
        want: []string{"foo", "bar", "baz"},
    },
    {
        name: "int keys",
        got:  getMapKeys(map[int]string{1: "foo", 2: "bar", 3: "baz"}),
        want: []int{1, 2, 3},
    },
    {
        name: "float64 keys",
        got:  getMapKeys(map[float64]bool{1.0: true, 2.5: false, 3.1415: true}),
        want: []float64{1.0, 2.5, 3.1415},
    },
}

// ...

func (us *UnitUtilSuite) TestUnitGetMapKeys() {
    for _, tt := range testUnitGetMapKeys {
        us.T().Run(tt.name, func(t *testing.T) {
            if !reflect.DeepEqual(tt.got, tt.want) {
                t.Errorf("got=%v; want=%v", tt.got, tt.want)
            }
        })
    }
}
卓越飞翔博客
上一篇: golang 中带有切片的并发映射
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏