首页 > 后端开发 > Golang > 正文

Golang模拟强制改变函数定义

WBOY
发布: 2024-02-12 12:33:08
转载
1220 人浏览过

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,因为大多数其他模拟问题你会遇到语言没有内置解决方案的情况。

以上是Golang模拟强制改变函数定义的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:stackoverflow.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!