Hi I would like to test or Mock a certain function and return a Mock response for this. To demonstrate below is my code
Sample.go
package main
import (
"fmt"
log "github.com/sirupsen/logrus"
)
var connectDB = Connect
func Sample() {
config := NewConfig()
response := connectDB(config)
fmt.Println(response)
log.Info(response)
}
func Connect(config *Config) string {
return "Inside the connect"
}
And my test is like this
Sample_test.go
package main
import (
"testing"
)
func TestSample(t *testing.T) {
oldConnect := connectDB
connectDB := func(config *Config) string {
return "Mock response"
}
defer func() { connectDB = oldConnect }()
Sample()
}
So when running go test I was expecting to receive and output of Mock response but I'm still getting Inside the connect. Is there something I'm missing here?
The use of a colon here creates a new function-scoped variable with the same name:
connectDB := func(config *Config) string {
return "Mock response"
}
Remove the colon to assign to the package variable.