创建一个模拟函数

时间:2018-07-25 10:57:14

标签: unit-testing go mocking testify

嗨,我想测试或模拟某个功能并为此返回模拟响应。下面演示我的代码

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响应,但我仍然在连接中获得。这里有我想念的东西吗?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

此处使用冒号会创建一个具有相同名称的新的作用域变量:

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

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

相关问题