go - golang 测试参数化

在 python 中我可以很容易地做到


@pytest.mark.parametrize('input, expected', [(1, 2), [2, 3]])

def test_tutu(input, expected):

    assert input + 1 == expected

我怎样才能在 golang 中做同样的事情?没有给自己写一个循环


func tutu(a int) int {

    return a + 1

}


func Test_tutu(t *testing.T) {

    tests := []struct {

        input    int

        expected int

    }{

        {input: 1, expected: 2},

        {input: 2, expected: 3},

    }


    for _, tt := range tests {

        t.Run("", func(t *testing.T) {

            assert.Equal(t, tutu(tt.input), tt.expected)

        })

    }

}

那么 golang 中的这个 python parametrize 相当于什么?


def parametrize(all_args_name: str, all_values: List[Any], fn: Callable):

    args_name = all_args_name.split(',')

    for values in all_values:

        args = {k: v for k, v in zip(args_name, values)}

        fn(**args)


拉丁的传说
浏览 89回答 2
2回答

慕后森

我找到了一种使用反射的方法func parametrize[V any, T any](fn T, allValues [][]V) {    v := reflect.ValueOf(fn)    for _, a := range allValues {        vargs := make([]reflect.Value, len(a))        for i, b := range a {            vargs[i] = reflect.ValueOf(b)        }        v.Call(vargs)    }}func tutu(a int) int {    return a + 1}func Test_tutu(t *testing.T) {    testsArgs := [][]any{        {t, 1, 2}, {t, 3, 4},    }    test := func(t *testing.T, input int, expected int) {        assert.Equal(t, tutu(input), expected)    }    parametrize(test, testsArgs)}

慕少森

GO 拥有的最接近的东西是subtests,但你仍然需要编写for循环,就像你在第二个例子中所做的那样。
打开App,查看更多内容
随时随地看视频慕课网APP