如何 mock/unittest 嵌套函数

How to mock/unittest nested function

我有一个函数在其他函数中被调用。

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
 }

unit_test

  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.How 要在测试期间在此 get_dict_function 中传递 getMap 值?*

任何指示都会有帮助吗?

假设您在模拟时遇到困难 http.Client,我想建议以下选项。

1.重构代码

您需要重构代码,以便您可以将可模拟的依赖项传递给您想要测试的函数。

例如,

重构 func send_api(client *http.Client,url string) map[string]string,error 以便它 api 请求和 getting/parsing 数据,但从中调用另一个函数,该函数进行进一步处理(实际上你想测试和不是 http.Client 部分)。

但是,使用这种方法,您可能无法测试端到端流程。但您可以单独测试这些功能。

2。模拟 http.Client

同样,您可能需要重构代码。可以找到一些相关文章 here

更新:推荐观看justforfunc #16: unit testing HTTP servers