douwen3198 2018-02-13 00:24
浏览 3
已采纳

Go-表驱动测试助手功能

I've found so many good examples of the table driven test, but it seems no ones written about the next step of creating a helper test method to pass in the functions you want to test. So that this part of the code doesn't have to repeat for every function you want to test:

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

* UPDATED I have this code, now working (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("
%v(%v)
 expected: %v
 actual: %v
", testingMethod, tt.n, tt.expected, actual)
        }
    }
}

But I was having trouble with the types or pointer or something for passing in a struct of test cases and the function to test in the table driven test loop. I'm getting this error in the code:

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

This was the closest I've found written about a go test helper function but it doesn't pass in a testcases struct or a function to test against: https://routley.io/tech/2017/11/05/intermediate-go-testing.html

Go TDD!

  • 写回答

1条回答 默认 最新

  • dongpobo6009 2018-02-13 00:45
    关注

    I think helper methods for table-driven tests aren't common because the "table" type will probably change between each test. This is because the table includes the inputs and expected outputs, and those changing result in a different type.

    The error you're getting is because you're trying to use one type where a different one is expected. You might be able to coerce curPairInputTestCases to a testCasesStructArray, but as soon as you make some changes to the struct type they will be incompatible.

    Small nitpick: []testCasesStruct is a slice and not an array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了