为了账号安全,请及时绑定邮箱和手机立即绑定

Go 包函数中的模拟函数

Go 包函数中的模拟函数

Go
呼如林 2023-07-17 17:56:23
我正在尝试模拟在我的 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 回答

?
慕神8447489

TA贡献1780条经验 获得超1个赞

这是解决方案


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)

    })

}


查看完整回答
反对 回复 2023-07-17
  • 1 回答
  • 0 关注
  • 68 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信