首頁  >  文章  >  後端開發  >  Golang模擬強制改變函數定義

Golang模擬強制改變函數定義

WBOY
WBOY轉載
2024-02-12 12:33:081221瀏覽

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刪除