go - 在 Go 包函数中模拟函数

标签 go testing mocking

我正在尝试模拟在我的 Go 代码中的 API 函数调用中使用的 HTTP 客户端。

import (
    "internal.repo/[...]/http"
    "encoding/json"
    "strings"
    "github.com/stretchr/testify/require"
)

func CreateResource(t *testing.T, url string, bodyReq interface{}, username string, password string, resource string) []byte {
    bodyReqJSON, err := json.Marshal(bodyReq)

    if err != nil {
        panic(err)
    }

    headers := make(map[string]string)
    headers["Content-Type"] = "application/json"

    logger.Logf(t, "*************************** CREATE a temporary test %s ***************************", resource)

    // this func below should be mocked
    statusCode, body := http.POST(t, url, bodyReqJSON, headers, username, password)

    require.Equal(t, statusCode, 201, "******ERROR!! A problem occurred while creating %s. Body: %s******", resource, strings.TrimSpace(string(body)))

    return body
}

我想模拟我的 http.POST 函数,它是内部 HTTP 包的一部分,这样我就不需要实际进行在线调用,也不需要离线隔离测试。

是否有替代方法来依赖注入(inject)模拟结构来实现假设的 HTTP 接口(interface)?

你会怎么做这样的事情?

最佳答案

这是解决方案,感谢@Peter。

import (
    "net/http"
    "net/http/httptest"
    "testing"

    "github.com/stretchr/testify/assert"
)

func TestCreateResource(t *testing.T) {
    t.Run("successful", func(t *testing.T) {
        server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            w.WriteHeader(201)
        }))
        defer server.Close()

        o := CreateResource(t, server.URL, nil, "admin", "password", "resource")
        assert.Equal(t, []byte{}, o)
    })
}

关于go - 在 Go 包函数中模拟函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57823737/

相关文章:

javascript - Mocha 'before each hook' 消息为红色。我怎么知 Prop 体出了什么问题?

scala - 模拟 Scala 对象和函数

unit-testing - 单元测试和模拟 Node JS 网络/套接字事件

go - 在go中复制一个文件夹

go - 处理应用程序中的 NULL 值并发送到数据库

go - 在 go 中使用回调和函数作为类型

go - reader.ReadLine() 在 Scanner.Scan() 调用后不会前进

java - 为什么 testNG 跳过我的测试?

python - 这个(冗余?)python 表达式的含义是什么?

java - JMock jar 不适用于 Android 测试项目(项目未构建)