声明为变量的函数的 Golang 测试(作证)

Golang testing of functions declared as variable (testify)

我在使用 testify 触发在 golang 中声明为变量的函数时遇到问题。

测试和函数都在同一个包中声明。

var testableFunction = func(abc string) string {...}

现在我有一个不同的文件,单元测试调用 testableFunction

func TestFunction(t *testing.T){
     ...
     res:=testableFunction("abc")
     ...
}

go test 调用 TestFunction 不会触发任何异常,但 testableFunction 实际上永远不会 运行。为什么?

那是因为您的 testableFunction 变量在代码的其他地方被赋值。

看这个例子:

var testableFunction = func(s string) string {
    return "re: " + s
}

测试代码:

func TestFunction(t *testing.T) {
    exp := "re: a"
    if got := testableFunction("a"); got != exp {
        t.Errorf("Expected: %q, got: %q", exp, got)
    }
}

运行 go test -cover:

PASS
coverage: 100.0% of statements
ok      play    0.002s

显然,如果在测试执行之前将新函数值分配给 testableFunction,那么用于初始化变量的匿名函数将不会被测试调用。

为了演示,将您的测试函数更改为:

func TestFunction(t *testing.T) {
    testableFunction = func(s string) string { return "re: " + s }

    exp := "re: a"
    if got := testableFunction("a"); got != exp {
        t.Errorf("Expected: %q, got: %q", exp, got)
    }
}

运行 go test -cover:

PASS
coverage: 0.0% of statements
ok      play    0.003s