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

标签 unit-testing go net-http

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

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}       
}

然后这个函数在ma​​in()函数中被调用

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

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

关于unit-testing - 如何模拟/单元测试嵌套函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45050191/

相关文章:

python - 如何在 Django 中使用验证码字段对表单进行单元测试?

javascript - 在 Javascript 中引用 Go 数组

go - Go中如何调整二维数组的大小?

azure - coverlet 不会在 azure devops 中创建报告

javascript - 如何在 Jasmine 中强制执行默认超时间隔?

unit-testing - 使用 Fixtures 加载后删除 fixtures

go - 如何配置 go 命令以使用代理?

ruby-on-rails - 以法拉第为参数发布图像

ssl - 如何在 GO 中创建带有 ca 证书的 tls 客户端?

ruby - 使用 Net::HTTP block 形式的 HTTPS 请求——这可能吗?