亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 http 作為依賴項進行單元測試

如何使用 http 作為依賴項進行單元測試

Go
白豬掌柜的 2023-05-15 15:35:07
我有以下按預期工作的功能?,F在我想為它運行一個單元測試。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,        },    }
查看完整描述

2 回答

?
慕工程0101907

TA貢獻1887條經驗 獲得超5個贊

我建議看一下httptest包。它有一個非常適合您的假 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)

? }

}


查看完整回答
反對 回復 2023-05-15
?
墨色風雨

TA貢獻1853條經驗 獲得超6個贊

我會使用類似以下代碼的東西。用法是newTestServer(address).run()


import (

    "github.com/gorilla/mux"

    "net/http"

    "sync"

    "time"

)


type testServer struct {

    addr   string

    router *mux.Router

}


// addr can be e.g. `localhost:3030`

// -> your client will do request on `localhost:3030/some/endpoint/path`

func newTestServer(addr string) *testServer {

    router := mux.NewRouter()

    router.HandleFunc(

        "/some/endpoint/path",

        handleEndpoint,

    ).Methods(http.MethodPost)


    return &testServer{

        addr:   addr,

        router: router,

    }

}


func handleEndpoint(writer http.ResponseWriter, request *http.Request) {

    // your implementation

}


func (server *testServer) run() {

    wg := sync.WaitGroup{}

    wg.Add(1)

    go func() {

        wg.Done()

        if err := http.ListenAndServe(server.addr, server.router); err != nil {

            panic(err)

        }

    }()

    wg.Wait()                          // wait for goroutine starts

    time.Sleep(100 * time.Millisecond) // wait for listening starts

}

但我認為測試仍然不會通過。


// this will panic

// requires 2nd and 3rd item in an array

req.SetBasicAuth(cc[1], cc[2])


查看完整回答
反對 回復 2023-05-15
  • 2 回答
  • 0 關注
  • 141 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號