gpt4 book ai didi

unit-testing - Go - 表驱动测试辅助函数

转载 作者:数据小太阳 更新时间:2023-10-29 03:12:06 27 4
gpt4 key购买 nike

我发现了很多关于表驱动测试的好例子,但似乎没有人写过关于创建辅助测试方法以传递要测试的函数的下一步。这样就不必为您要测试的每个函数重复这部分代码:

func TestFib(t *testing.T) {
for _, tt := range fibTests {
actual := Fib(tt.n)
if actual != tt.expected {
t.Errorf("Fib(%d): expected %d, actual %d", tt.n, tt.expected, actual)
}
}
}
// from: https://medium.com/@matryer/5-simple-tips-and-tricks-for-writing-unit-tests-in-golang-619653f90742

* 已更新 我有这段代码,现在可以使用 ( https://gist.github.com/mikeumus/a97da2d65bfa4f5b92e13177f6a88922 ):

type testCasesStruct []struct {
n string
expected bool
}
type valUserInType func(string) bool

var curPairInputTestCases = []struct {
n string
expected bool
}{
{"1/d", false},
// continued test cases...
}

func TestGoPolSuite(t *testing.T) {
methodTester(t, validateCurPairInput, curPairInputTestCases)
}

func methodTester(t *testing.T, testingMethod valUserInType, testCases testCasesStruct) {
t.Helper()
for _, tt := range testCases {
actual := testingMethod(tt.n)
if actual != tt.expected {
t.Errorf("\n%v(%v)\n expected: %v\n actual: %v\n", testingMethod, tt.n, tt.expected, actual)
}
}
}

但是我在传递测试用例结构和在表驱动测试循环中测试的函数时遇到了类型或指针或其他问题。我在代码中收到此错误:

<罢工> cannot use curPairInputTestCases (type []struct { n string; expected bool }) as type testCasesStructArray in argument to methodTester

这是我发现的最接近 go 测试辅助函数的文章,但它没有传递测试用例结构或要测试的函数:https://routley.io/tech/2017/11/05/intermediate-go-testing.html

开始 TDD!

最佳答案

我认为表驱动测试的辅助方法并不常见,因为“表”类型可能会在每次测试之间发生变化。这是因为该表包含输入和预期输出,而这些更改会导致不同的类型。

您收到的错误是因为您试图在预期使用不同类型的地方使用一种类型。您可能能够将 curPairInputTestCases 强制转换为 testCasesStructArray,但是只要您对结构类型进行一些更改,它们就会不兼容。

小毛病:[]testCasesStruct 是 slice 而不是数组。

关于unit-testing - Go - 表驱动测试辅助函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48757718/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com