【发布时间】:2021-08-13 17:31:30
【问题描述】:
我想根据特定条件在 GoLang 中模拟 Rest API 调用。 例如,我有一个定义如下的方法:
func Method() {
resp1, err := DoSomething1()
resp2, err := DoSomething2()
}
func DoSomething1() (*http.Response, error) {
return Get(url string)
}
func DoSomething2() (*http.Response, error) {
return Get(url string)
}
现在,我想分别为每个 get 调用定义我的模拟响应。即当我从 Method() 调用 DoSomething1() 时,我想模拟 get 调用并返回响应 R1,当我从 Method() 调用 DoSomething2() 时,我想模拟 get 调用并返回响应 R2。
到目前为止,我已经能够通过将 Get 定义为接口并对其进行模拟来模拟单个 get 调用,该调用将为任何请求返回相同的响应,但是我正在尝试为每个调用定义响应。
下面是我定义的用于模拟 get/post 调用的模拟接口:
package clientMock
import (
"net/http"
)
type MockClient struct {
}
var (
GetMock func(url string, queryParams map[string]interface{}, headerParams map[string]interface{}) (*http.Response, error)
PostMock func(url string, reqBody interface{}, queryParams map[string]interface{}, headerParams map[string]interface{}) (*http.Response, error)
)
func (m MockClient) Get(url string, queryParams map[string]interface{}, headerParams map[string]interface{}) (*http.Response, error) {
return GetMock(url, queryParams, headerParams)
}
func (m MockClient) Post(url string, reqBody interface{}, queryParams map[string]interface{}, headerParams map[string]interface{}) (*http.Response, error) {
return PostMock(url, reqBody, queryParams, headerParams)
}
下面是我为测试 Method 定义的示例测试类,但是无法弄清楚当从 Method() 调用 DoSomething2() 时如何更改模拟响应:
func TestHandleSuccess(t *testing.T) {
resBody := `{"instance_url":"instance_url","access_token":"access_token"}`
r := ioutil.NopCloser(bytes.NewReader([]byte(resBody)))
clientMock.GetMock = func(url string, queryParams, headerParams map[string]interface{}) (*http.Response, error) {
return &http.Response{
StatusCode: 200,
Body: r,
}, nil
}
err := method.Method()
assert.Nil(t, err)
}
【问题讨论】:
标签: unit-testing go