douliwang6896 2019-09-06 14:14
浏览 105
已采纳

Go包功能中的模拟功能

I am trying to mock an HTTP client that's being used within an API function call in my Go code.

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
}

I'd like to mock my http.POST function that it's part of an internal HTTP package so that I do not need to actually make the online call, and isolate the test offline.

Is there an alternative way to dependency-inject a mock structure that implements an hypothetical HTTP interface?

How would you do something like this?

  • 写回答

1条回答 默认 最新

  • dongyuan6949 2019-09-06 14:50
    关注

    Here's the solution, thanks to @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)
        })
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突