Go包功能中的模拟功能

时间:2019-09-06 14:14:01

标签: 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程序包的一部分,因此我不需要实际进行在线调用并脱机测试。

是否有另一种方法来依赖注入一个实现假设的HTTP接口的模拟结构?

您将如何做这样的事情?

1 个答案:

答案 0 :(得分:1)

这是解决方案,感谢@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)
    })
}