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

I have a problem firing a function declared as variable in golang with testify.

Test and function both declared in same package.

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

now i have a different file with unit test calling testableFunction

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

Calling TestFunction with go test does not fire any exception, but testableFunction is actually never run. Why?

That's because your testableFunction variable gets assigned somewhere else in your code.

See this example:

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

Test code:

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

Running go test -cover:

PASS
coverage: 100.0% of statements
ok      play    0.002s

Obviously if a new function value is assigned to testableFunction before the test execution, then the anonymous function used to initialize your variable will not get called by the test.

To demonstrate, change your test function to this:

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)
    }
}

Running go test -cover:

PASS
coverage: 0.0% of statements
ok      play    0.003s