【问题标题】:Create a mock function创建模拟函数
【发布时间】:2018-07-25 10:57:14
【问题描述】:

您好,我想测试或模拟某个函数并为此返回一个模拟响应。下面演示的是我的代码

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 响应,但我仍然进入连接。我这里有什么遗漏吗?

【问题讨论】:

    标签: unit-testing go mocking testify


    【解决方案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)
    }
    

    【讨论】:

      【解决方案2】:

      这里使用冒号会创建一个新的同名函数范围变量:

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

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

      【讨论】:

        猜你喜欢
        • 2021-12-01
        • 2019-10-10
        • 2018-04-25
        • 2020-06-14
        • 1970-01-01
        • 2013-07-10
        • 2021-11-17
        • 2021-02-22
        • 1970-01-01
        相关资源
        最近更新 更多