创建模拟函数

Create a mock function

您好,我想测试或模拟某个功能,return 对此进行模拟响应。下面演示的是我的代码

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"
}

而我的测试是这样的

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()
}

所以当 运行 go test 我期待接收和输出 Mock response 但我仍然得到连接内部。我在这里遗漏了什么吗?

此处使用冒号创建了一个新的同名函数范围变量:

connectDB := func(config *Config) string {
    return "Mock response"
}

删除冒号以分配给包变量。

@jrefior 是正确的,但我建议使用接口进行模拟。当然,这取决于你,我打赌它更清晰,但代码更复杂:)

// 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)
}