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

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?

图片转代码服务由CSDN问答提供 功能建议

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

  import(
“ internal.repo /[...]/ http” 
“ encoding / json” 
“ strings” 
“ github.com  / stretchr / testify / require“ 
)
 
func CreateResource(t * testing.T,网址字符串,bodyReq接口{},用户名字符串,密码字符串,资源字符串)[] byte {
 bodyReqJSON,err:=  json.Marshal(bodyReq)
 
,如果出错!= nil {
 panic(err)
} 
 
标头:= make(map [string] string)
标头[“ Content-Type”]  =“ application / json” 
 
 logger.Logf(t,“ ***************************创建一个临时测试%s  *******************************“,资源)
 
 //下面的函数必须被模拟
 statusCode,正文:=  http.POST(t,url,bodyReqJSON,标头,用户名,密码)
 
 require.Equal(t,statusCode,201,“ ****** ERROR !!!!在创建%s时出现问题。  %s ******“,资源,字符串。TrimSpace(strin  g(body)))
 
返回正文
} 
   
 
 

我想模拟我的 http.POST 函数 它是内部HTTP程序包的一部分,因此我不需要实际进行在线调用,也无需脱机隔离测试。

是否有另一种方法可以依赖注入模拟结构

您将如何执行这样的操作?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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)
        })
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题