登录
首页 >  Golang >  Go问答

使用表格驱动测试(Go)来测试通用函数

来源:stackoverflow

时间:2024-02-26 08:57:28 297浏览 收藏

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《使用表格驱动测试(Go)来测试通用函数》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

我们正在集思广益,讨论使用表驱动测试来测试通用函数的可能方法。 乍一看似乎很复杂。

我们想要实现的是在测试表结构中有一个字段,该字段可以是通用函数接受的任何类型。但是,您似乎无法使用 any 接口来实现这一点。

我们提出了以下解决方案:

示例函数

func ptrto[t any](t t) *t {
    return &t
}

示例测试

func TestPtrTo(t *testing.T) {

    string1 := "abcd"

    trueVar := true

    testCases := []struct {
        testDescription string
        input           interface{}
        expectedOutput  interface{}
    }{
        {
            testDescription: "string",
            input:           string1,
            expectedOutput:  &string1,
        },
        {
            testDescription: "bool",
            input:           trueVar,
            expectedOutput:  &trueVar,
        },
    }

    for _, testCase := range testCases {
        t.Run(testCase.testDescription, func(t *testing.T) {
            switch concreteTypeInput := testCase.input.(type) {
            case string:
                output := PtrTo(concreteTypeInput)
                assert.Equal(t, testCase.expectedOutput, output)
            case bool:
                output := PtrTo(concreteTypeInput)
                assert.Equal(t, testCase.expectedOutput, output)
            default:
                t.Error("Unexpected type. Please add the type to the switch case")
            }
        })
    }
}

尽管如此,感觉并不是最佳。

您认为这个解决方案怎么样?

您还看到其他替代方案吗?


正确答案


模板化的辅助函数可以为您提供我认为您正在寻找的语义:

package main

import (
    "testing"

    "github.com/google/go-cmp/cmp"
)

type testCase[T any] struct {
    desc string
    in   T
    want *T
}

func ptrToTest[T any](t *testing.T, tc testCase[T]) {
    t.Helper()
    t.Run(tc.desc, func(t *testing.T) {
        got := PtrTo(tc.in)
        if diff := cmp.Diff(tc.want, got); diff != "" {
            t.Fatalf("got %v, want %v", got, tc.want)
        }
    })
}

func TestPtrTo(t *testing.T) {
    string1 := "abcd"
    ptrToTest(t, testCase[string]{
        desc: "string",
        in:   string1,
        want: &string1,
    })

    trueVar := true
    ptrToTest(t, testCase[bool]{
        desc: "bool",
        in:   trueVar,
        want: &trueVar,
    })
}

话虽这么说,我同意 @blackgreen 的观点,即 ptrto 函数对于这样的测试来说太微不足道了,没有意义。希望这对于更复杂的逻辑有用!

理论要掌握,实操不能落!以上关于《使用表格驱动测试(Go)来测试通用函数》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>