亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 127 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號