卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章35441本站已运行396

Golang模拟强制改变函数定义

golang模拟强制改变函数定义

php小编小新今天为大家带来了关于Golang模拟强制改变函数定义的介绍。Golang是一种高效、简洁的编程语言,具有强大的类型系统。然而,在某些情况下,我们可能需要修改已有函数的定义,以满足特定的需求。本文将向大家介绍如何在Golang中模拟强制改变函数定义的方法,让我们一起来探索吧!

问题内容

我有以下功能:

func getprice(date string) {
  url := (fmt.printf("http://endponint/%s", date))
    resp, err := http.get(url)
    // unmarshall body and get price
    return price
}

为了对该函数进行单元测试,我被迫重构为:

func getprice(client httpclient, date string) {
  url := (fmt.printf("http://endponint/%s", date))
    resp, err := client.get(url)
    // unmarshall body and get price
    return price
}

我的测试如下所示:

type MockClient struct {
    Response *http.Response
    Err      error
}

func (m *MockClient) Get(url string) (*http.Response, error) {
    return m.Response, m.Err
}

mockResp := &http.Response{
    StatusCode: http.StatusOK,
    Body:       ioutil.NopCloser(strings.NewReader("mock response")),
}

client := &MockClient{
    Response: mockResp,
    Err:      nil,
}

data, err := getData(client, "http://example.com")

这是在 go 中进行测试的唯一方法吗?没有办法模拟未注入到函数中的 api 吗?

解决方法

使用 go 进行 http 测试的惯用方法是使用 http/httptest ( 示例)

就您而言,您所需要做的就是使基本 url 可注入:

var apiendpoint = "http://endpoint/"

func getprice(date string) (int, error) {
  url := (fmt.printf("%s/%s", apiendpoint, date))
  resp, err := http.get(url)
  // unmarshall body and get price
  return price, nil
}

然后在每个测试中:

srv := httptest.newserver(http.handlerfunc(func(w http.responsewriter, r *http.request) {
    // write the expected response to the writer
}))
defer srv.close()
apiendpoint = srv.url
price, err := getprice("1/1/2023")
// handle error, check return

更好的设计是将您的 api 包装在客户端 struct 中,并使 getprice 成为接收器方法:

type priceclient struct {
    endpoint string
}

func (pc *priceclient) getprice(date string) (int, error) {
  url := (fmt.printf("%s/%s", pc.endpoint, date))
  resp, err := http.get(url)
  // unmarshall body and get price
  return price, nil
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    // Write the expected response to the writer
}))
defer srv.Close()
c := &PriceClient{Endpoint: srv.URL}
price, err := c.GetPrice("1/1/2023")
// Handle error, check return

为了将来的参考,你还应该看看gomock,因为大多数其他模拟问题你会遇到语言没有内置解决方案的情况。

卓越飞翔博客
上一篇: CORS grpc 网关 GoLang
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏