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

huangapple go评论80阅读模式
英文:

Golang testing of functions declared as variable (testify)

问题

我在使用testify库时遇到了一个问题,无法调用以变量形式声明的函数。测试和函数都在同一个包中声明。

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

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

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

使用go test命令运行TestFunction时没有触发任何异常,但实际上testableFunction从未运行。为什么会这样?

英文:

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?

答案1

得分: 3

这是因为你的 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
英文:

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

huangapple
  • 本文由 发表于 2016年11月28日 22:31:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/40846738.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定