3

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 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer! Do u know how to reassign it back to the initial function?
I think I've found the solution. Simply create a temporary variable to keep the initial function. After the second assignment, then put the initial function back to the variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.