我有一个函数在其他函数中被调用。
send_api.go
function *send_api*(client *http.Client,url string) map[string]string,error {
//send api request and parse the response and return the dict
return dictmap
for eg:{apple fruit}
}
然后这个函数在main()函数中被调用
func *main()*{
getmap :=send_api(client *http.Client,"test.com")
}
good.go
func *get_dict_key*(key string) string,error {
value,ok := get_map[key]
if !ok {
return fmt.Errorf("value is nil")
}
return value ,nil
}
function *good*(client *http.client, key string) {
//get a dictionary value
dcmap,err := get_dict_key("apple")
if err != nil {
panic(err)
}
value := dcmap[key]
//use the value to do other processing
}
单元测试
func Test_good(t *testing.T) {
Convey("AND quadra and conusl dcs are mapped",t, func() {
mockResponses := send mock GET request to the URL and receive a response{"apple":"fruit"}
}
server, client := tools.TestClientServer(&mockResponses)
defer server.Close()
getMap := send_api(client.HTTPClient, "http://test")
//At this point getMAP has value {'apple' 'fruit'}
**q1.How to pass getMap value inside this get_dict_fkey function during testing?**
value := get_dict_key("apple")
good(client,"apple") #error:(value is nil)
Q1。 **q1.如何在测试期间在这个get_dict_function中传递getMap值?*
任何指针都会有帮助吗?
最佳答案
假设您在模拟 http.Client 时遇到困难,我想建议以下选项。
<强>1。重构代码
您需要重构代码,以便您可以将可模拟的依赖项传递给您想要测试的函数。
例如,
重构 func send_api(client *http.Client,url string) map[string]string,error
以便它执行 api 请求和获取/解析数据,但从中调用另一个函数,该函数做进一步的处理(实际上你想测试而不是 http.Client 部分)。
但是,使用这种方法,您可能无法测试端到端流程。但您可以单独测试这些功能。
<强>2。模拟 http.Client
同样,您可能需要重构您的代码。可以找到一些相关文章here
关于unit-testing - 如何模拟/单元测试嵌套函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45050191/