登录
首页 >  Golang >  Go问答

用http包装函数作为依赖项进行单元测试

来源:stackoverflow

时间:2024-03-06 08:09:25 429浏览 收藏

你在学习Golang相关的知识吗?本文《用http包装函数作为依赖项进行单元测试》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!

问题内容

我有以下函数,在 @poy 的帮助下,我能够为其创建模拟以对其进行单元测试。

现在的问题是我已经有了还需要测试的包装函数

这是原始功能,已进行工作测试

func httpreq(cc []string, method string, url string) ([]byte, error) {
    httpclient := http.client{}
    req, err := http.newrequest(method, url, nil)
    if err != nil {
        return nil, errors.wrap(err, "failed to execute http request")
    }
    //here we are passing user and password
    req.setbasicauth(cc[1], cc[2])
    res, err := httpclient.do(req)
    if err != nil {
        fmt.error(err)
    }
    val, err := ioutil.readall(res.body)
    if err != nil {
        fmt.error(err)
    }
    defer res.body.close()
    return val, nil
}

这是按预期工作的测试,该测试使用 https://golang.org/pkg/net/http/httptest/ 以模拟 http 请求。

func test_httpreq(t *testing.t){

  expectedvalue = "some-value"
  server := httptest.newserver(http.handlerfunc(func(w http.responsewriter, r *http.request){

    u,p,ok := r.basicauth()
    if !ok || u != "fakeuser" || p != "fakepassword" {
      t.fatal("wrong auth")
    }
    w.write([]byte(expectedvalue))
  })

  val, err := httpreq(
   []string{"fakeuser", "fakepassword"}, 
   http.methodpost, 
   server.url,
  )

  if err != nil{
    t.fatal(err)
  }

  if val != expectedvalue {
    t.fatalf("expected %q to equal %q", val, expectedvalue)
  }

现在的问题是我有另一个函数调用上述函数也需要测试。

这是使用 httpreq 的函数,我也需要为其创建测试

func (c *Service) invoke(Connection Connection, args []string) {
    service, err := c.getService(Connection, args)

    serviceC, err := c.getServiceK(service, []string{"url", “user”, “id”})
    c := strings.Fields(serviceC)
        //—————Here we are using the http function again 
    val, err := httpReq(c[1], c[1],”post”, c[0])
    if err != nil {
        fmt.println(err)
    }
    fmt.Print(string(val))
}

现在,当我对其进行测试时,我在 http 请求方法 中遇到了错误,因为在这里我无法模拟 http。

golang中有没有technique哪位可以帮助这种情况? 我已经搜索过它,比如依赖注入,并发现也许接口可以提供帮助,但由于这是http,我不知道如何做到这一点。

任何具有此背景的示例都会对我非常有帮助。


解决方案


服务对象可以有这样的接口

type service struct {
    servicek typek
    servicehttp servicehttp // of type interface hence can be mocked
}

普通应用程序代码可以使用实际对象初始化服务。测试将有模拟对象

type req struct {
}

type resp struct {
}

type servicehttp interface{
    httpreq(params req)(resp, error)
}

type implementation struct {
}

func (i *implementation)httpreq(params req)(resp, error){
   // buid http request
}

func (c *service) invoke(connection connection, args []string) {

    service, err := c.getservice(connection, args)

    servicec, err := c.getservicek(service, []string{"url", “user”, “id”})
    c := strings.fields(servicec)

    serviceimp := c.getserviceimp()

    // init params with the required fields
    val, err := c.httpreq(params)
    if err != nil {
      fmt.println(err)
    }
    fmt.print(string(val))

}

当您运行测试时,您可以使用返回虚拟响应的模拟实现来初始化服务对象。

type MockImplementation struct {
}

func (i *MockImplementation)HttpReq(Resp, error){
    // return mock response
}

func TestMain(){
  services := {
     serviceHttp:MockImplementation{},
     serviceK: typeK{}, // initialise this
  }
}

这是测试它的方法之一。其他方式可能是我猜测 httpreq 返回 http.responsewriter 的位置,您可以使用 httptest.responserecorder 来测试它。

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>