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

标签 go 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

关于声明为变量的函数的 Golang 测试(作证),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40846738/

相关文章:

go - 如何将 Sentry 与 go.uber.org/zap/zapcore 记录器结合使用

go - 我有一个具有4个物理核心的处理器,每个核心有2个线程。但是,为什么runtime.NumCPU()返回4而不是8?

go - bufio.NewReader 总是创建一个新行 :/

unit-testing - GoLang Sarama ConsumerGroup模拟

go - 模拟时如何不使用界面?

go - Testify 套件中的 SetupSuite 和 SetupTest 之间的区别

unit-testing - 错误 : suite. go:61: test paniced: reflect: Call with too few input arguments

image - 去画图像蒙版

file-upload - golang - 如何检查multipart.File信息

Go:使用数据库初始化从多个包运行测试