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.
@jrefior is correct, but I'd suggest to use interface for mocking. Of course, it's up to you, bet for me it is more clear, but more complicated code :)
// lack some fields :)
type Config struct {
}
// Use interface to call Connect method
type IConnection interface {
Connect(config *Config) string
}
// Real connection to DB
type Connection struct {
}
func (c Connection) Connect(config *Config) string {
return "Inside the connect"
}
// Mock connection
type MockConnection struct {
}
func (c MockConnection) Connect(config *Config) string {
return "Mock connection"
}
// Accepts interface to connect real or mock DB
func Sample(con IConnection) {
log.Println(con.Connect(nil))
}
func main() {
realConnection := Connection{}
Sample(realConnection)
mockConnection := MockConnection{}
Sample(mockConnection)
}