如何模拟/单元测试嵌套函数

huangapple go评论92阅读模式
英文:

How to mock/unittest nested function

问题

我可以帮你翻译这段代码。以下是翻译的结果:

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

send_api.go

func send_api(client *http.Client, url string) (map[string]string, error) {
    // 发送 API 请求并解析响应,返回字典
    return dictmap, nil
    // 例如:{apple: fruit}
}

然后这个函数在 main() 函数中被调用:

func main() {
    getmap, err := 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
}

func good(client *http.Client, key string) {
    // 获取字典的值
    dcmap, err := get_dict_key("apple")
    if err != nil {
        panic(err)
    }
    value := dcmap[key]

    // 使用该值进行其他处理
}

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")
    // 此时 getMap 的值为 {"apple": "fruit"}
    // 如何在测试期间将 getMap 的值传递给 get_dict_key 函数?
    value := get_dict_key("apple")
    good(client, "apple") // 错误:value is nil
}

问题1:在测试期间如何将 getMap 的值传递给 get_dict_key 函数?

希望这些信息对你有所帮助!

英文:

I have a function which is getting called inside other 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}       
}

Then this function is getting called in main() function

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 to pass getMap value inside this get_dict_function during testing?

Any pointer would be helpful?

答案1

得分: 2

假设你在模拟http.Client时遇到了困难,我想提供以下几个选项。

1. 重构代码

你需要以这样的方式重构代码,以便可以将可模拟的依赖项传递给要测试的函数。

例如,

重构func send_api(client *http.Client,url string) map[string]string,error,使其执行API请求和获取/解析数据,但从中调用另一个函数,该函数执行进一步的处理(实际上,你想要测试的是这部分,而不是http.Client部分)。

但是,使用这种方法,你可能无法测试端到端的流程。但你可以单独测试这些函数。

2. 模拟http.Client

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

更新:建议观看justforfunc #16: unit testing HTTP servers

英文:

Assuming you are facing difficulty to mock http.Client, I would like to suggest following options.

1. Refactor the code

You need to refactor the code in such a way that you can pass the mockable dependencies to function that you would like to test.

For example,

Refactor func send_api(client *http.Client,url string) map[string]string,error so that it does api request and getting/parsing data, but call another function from it, which does the further processing (that actually you would like to test and not the http.Client part).

But, with this approach, you may not be able to test end to end flow. But you can test those functions separately.

2. Mock http.Client

Again, you may need to refactor your code. Some related article can be found here

Update: Recommending to watch justforfunc #16: unit testing HTTP servers

huangapple
  • 本文由 发表于 2017年7月12日 14:38:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/45050191.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定