如何为go web api编写单元测试

时间:2017-06-20 01:55:19

标签: go

我正在为golang web API编写单元测试。 我有一个像 domain.com/api/user/current 这样的API 此API将返回用户登录的信息。 我使用 http.NewRequest 来请求此API。但它不起作用。

那么如何使用权限自动调用此API?

func TestGetCurrentUserLogged(t *testing.T) {
    assert := assert.New(t)

    var url = "http://example.com/user/current";
    req, _ := http.NewRequest(http.MethodGet, url, nil)
    client := &http.Client{}
    //req.Header.Add("Cookie", "")//
    res, _ := client.Do(req)
    if res.StatusCode == http.StatusBadGateway {
        assert.True(false)
    }

    body, err := ioutil.ReadAll(res.Body)
    defer res.Body.Close()
    if err != nil {
        t.Errorf("Error 1 API: %v", err.Error())
    }
    var response map[string]interface{}
    err = json.Unmarshal(body, &response)
    if err != nil {
        t.Errorf("Error 2 API:%v", err.Error())
    }
}

1 个答案:

答案 0 :(得分:0)

这是我测试我的服务器......虽然我相信这是更多功能测试,这更像你上面想要做的。我在代码中添加了注释,以便您了解正在发生的事情。当然,您必须根据自己的需要对其进行修改。

type payload struct {
    WhateverElse interface{}
    Error        error
}

func TestSite(t *testing.T) {
    ctx := context.Background()
    ctx, cancel := context.WithCancel(ctx)
    defer cancel()
    // I'm using the Bone router in this example but can be replaced with most routers
    myRouter := bone.New()
    myRouter.GetFunc("/foo/:bar", routes.WipeCache)
    myRouter.NotFoundFunc(routes.NotFound)
    n := negroni.New()
    n.UseHandler(wrappers.DefaultHeaders(myRouter))
    // start an instance of the server on port 8080
    // to run different tests in different functions, change the port
    srv := &http.Server{Addr: ":8080", Handler: n}
    on := make(chan struct{}, 1)
    go func(on chan struct{}) {
        on <- struct{}{}
        log.Fatal(srv.ListenAndServe())
    }(on)
    // shutdown the server when i'm done
    srv.Shutdown(ctx)
    // the channel on is not really needed, but I like to have it to make sure srv.ListenAndServe() has had enough time to warm up before I make a requests. So i block just a tiny bit.
    <-on

    // create the client requests to test the server
    client := &http.Client{
        Timeout: 1 * time.Second,
    }

    // Test logic
    req, err := http.NewRequest("GET", "http://localhost:8080/foo/bar", nil)
    if err != nil {
        t.Errorf("An error occurred. %v", err)
    }
    resp, err := client.Do(req)
    if err != nil {
        t.Errorf("An error occurred. %v", err)
    }
    defer resp.Body.Close()
    ctx.Done()

    if status := resp.StatusCode; status != http.StatusOK {
        t.Errorf("Status code differs. Expected %d .\n Got %d instead", http.StatusOK, status)
    }
    var data payload
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        t.Errorf("An error occurred. %v", err)
    }
    json.Unmarshal(body, &data)

    if data.Error != nil {
        t.Errorf("An error occurred. %v", err)
    }
}