Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 如何使用http作为依赖项进行单元测试_Unit Testing_Go - Fatal编程技术网

Unit testing 如何使用http作为依赖项进行单元测试

Unit testing 如何使用http作为依赖项进行单元测试,unit-testing,go,Unit Testing,Go,我有下面的功能,它可以正常工作。 现在我想为它运行一个单元测试 func httpClient(cc []string,method http) ([]byte, error) { httpClient := http.Client{} req, err := http.NewRequest(http.MethodPost, c[0]+"/oauth/token", nil) if err != nil { fmt.error(err) }

我有下面的功能,它可以正常工作。 现在我想为它运行一个单元测试

func httpClient(cc []string,method http) ([]byte, error) {
    httpClient := http.Client{}
    req, err := http.NewRequest(http.MethodPost, c[0]+"/oauth/token", nil)
    if err != nil {
        fmt.error(err)
    }
    //Here we are passing user and password
    req.SetBasicAuth(c[1], c[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
}
问题是我需要一些东西来伪造http调用, 我尝试了以下方法,更改方法签名并将方法和url作为参数。 问题是我不知道如何在
POST
方法中伪造

这是更改的代码,以使测试更容易

func httpClient(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
}
这是我尝试的测试,但仍然不起作用,因为我需要以某种方式伪造post方法

func Test_httpClient(t *testing.T) {
    type args struct {
        params    []string
        method string
        url    string
    }
    tests := []struct {
        name    string
        args    args
        want    []byte
        wantErr bool
    }{
        {
            name:    "httpCallTest",
            args:{{"fakeuser", "fakepasswword"},{"post"},{"/any/url"}},
            want:    nil,
            wantErr: false,
        },

    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got, err := httpClient(tt.args.params, tt.args.method, tt.args.url)
            if (err != nil) != tt.wantErr {
                t.Errorf("httpClient() error = %v, wantErr %v", err, tt.wantErr)
                return
            }
            if !reflect.DeepEqual(got, tt.want) {
                t.Errorf("httpClient() = %v, want %v", got, tt.want)
            }
        })
    }
}

我建议你看看包装。它有一个假的HTTP服务器,非常适合您

func Test_httpClient(t *testing.T){
  var called bool
  defer func(){
    if !called{
      t.Fatal("expected endpoint to be called")
    }
  }()
  expectedValue = "some-value"

  server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
    called = true
    u,p,ok := r.BasicAuth()
    if !ok || u != "fakeuser" || p != "fakepassword" {
      t.Fatal("wrong auth")
    }
    w.Write([]byte(expectedValue))
  })

  val, err := httpClient(
   []string{"fakeuser", "fakepasswword"}, 
   http.MethodPost, 
   server.URL,
  )

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

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

我会使用下面的代码。用法是
newTestServer(地址)。run()

但我认为考试还是不会通过

// this will panic
// requires 2nd and 3rd item in an array
req.SetBasicAuth(cc[1], cc[2])

非常感谢。我不确定我是否明白,你能用我的上下文扩展你的例子吗?我需要更改的是
方法
,在“test method”中,我更新了示例以包含完整的测试。我认为生产方面不需要测试更改。谢谢,顺便说一句,你说“我认为生产端不需要测试更改。”代码(第二次迭代)看起来还好吗?我会说是的。它采用允许测试服务器传入其URL的URL。谢谢,我会检查它并让您知道仅供参考:使用表测试非常好!将它们用于单个案例。。。没有必要。
// this will panic
// requires 2nd and 3rd item in an array
req.SetBasicAuth(cc[1], cc[2])