2016-11-28 9 views
2

testifyでgolangで変数として宣言された関数を起動するときに問題があります。変数として宣言された関数のGolangテスト(証言)

テストと関数の両方が同じパッケージで宣言されています。

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

は、今私は、ユニットテストは、任意の例外を発生しません go testでTestFunctionを呼び出す

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

testableFunctionに呼び出して別のファイルを持っていますが、testableFunctionは、実際に実行されることはありません。どうして?

答えて

2

あなたの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に割り当てられている場合、あなたのバリアブルを初期化するために使用される無名関数ルはテストによって呼び出されません。

、実証テスト機能は、これに変更するには:

go test -coverを実行
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) 
    } 
} 

PASS 
coverage: 0.0% of statements 
ok  play 0.003s 
関連する問題