unit-testing - 在测试中模拟调用服务器的 Golang 函数
问题描述
我不负责维护被测代码库,但我有这种方法可以尝试测试,它会命中一个真实的服务器:
func (a *APICoreSt) CallServer(context interface{}, apiType APIType, apiURL string, header map[string]string, jsonBody []byte) CallResultSt {
var (
Url = a.BaseURL + apiURL
err error
res *http.Response
resBody json.RawMessage
hc = &http.Client{}
req = new(http.Request)
)
req, err = http.NewRequest(string(apiType), Url, bytes.NewBuffer(jsonBody))
if err != nil {
//Use a map instead of errorSt so that it doesn't create a heavy dependency.
errorSt := map[string]string{
"Code": "ez020300007",
"Message": "The request failed to be created.",
}
logger.Instance.LogError(err.Error())
err, _ := json.Marshal(errorSt)
return CallResultSt{DetailObject: err, IsSucceeded: false}
}
for k, v := range header {
req.Header.Set(k, v)
}
res, err = hc.Do(req)
if res != nil {
resBody, err = ioutil.ReadAll(res.Body)
res.Body = ioutil.NopCloser(bytes.NewBuffer(resBody))
}
return CallResultSt{resBody, logger.Instance.CheckAndHandleErr(context, res)}
}
显然,由于这是一个单元测试,我不想把这个要求当真,而且测试取决于外部因素。有没有办法在不触及这个函数本身的情况下注入任何假货/模拟物(触摸它实际上不是我的工作)?
解决方案
推荐阅读
- python - matplotlib 如何设置它的 y 轴值?
- dynamics-crm - 舍入 Dynamics 365 中的计算字段
- maven - Checkstyle 在构建或验证阶段不起作用
- python - 为什么我的 for 循环试图从标题行而不是第一行开始?
- mysql - 带有 MySQL 数据库的 Docker Spring Boot,连接被拒绝
- sql - 改进查询以减少重复
- python - 张量流动物园模型对象检测 - 大小会影响结果吗?
- sql - 将 PostgreSQL 查询转换为 SQL Server 查询
- javascript - 状态更改时重新呈现导航栏
- python - ModuleNotFoundError:没有名为“模型”的模块并且都是正确的