如何为GoWebAPI编写单元测试

如何为GoWebAPI编写单元测试,go,Go,我正在为GolangWebAPI编写一个单元测试。 我有一个类似domain.com/API/user/current的API。 此API将返回用户登录的信息。 我使用http.NewRequest向这个API发出请求。但它不起作用。 那么,如何使用日志记录的权限对该API进行自调用? func TestGetCurrentUserLogged(t *testing.T) { assert := assert.New(t) var url = "http://example.c

我正在为GolangWebAPI编写一个单元测试。 我有一个类似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())
    }
}

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

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)
    }
}
类型有效负载结构{
还有什么接口{}
误差
}
func测试站点(t*testing.t){
ctx:=context.Background()
ctx,cancel:=上下文。带取消(ctx)
推迟取消
//在本例中,我使用的是Bone路由器,但可以用大多数路由器替换
myRouter:=bone.New()
myRouter.GetFunc(“/foo/:bar”,routes.WipeCache)
myRouter.NotFoundFunc(routes.NotFound)
n:=negroni.New()
n、 UseHandler(wrappers.DefaultHeaders(myRouter))
//在端口8080上启动服务器实例
//要在不同的功能中运行不同的测试,请更改端口
srv:=&http.Server{Addr::8080',处理程序:n}
on:=make(chan结构{},1)
go func(关于chan结构{}){

“但它不起作用。”不是问题描述。请更具体一点。您有权限问题吗?现在,我尝试调用登录服务,然后获取cookie,然后将其添加到header Requests中。如前所述,您的测试只有在服务器正在运行时才会起作用。我不知道您是否在测试中的其他地方启动它,但这会使测试不必要地繁重;您可以直接将请求和一个
httptest.ResponseRecorder
传递给您的HTTP处理程序来测试它们,而不是使用客户端发出请求。是的,您纠正了,我的服务器没有运行,我只在服务器启动时运行测试。那么,启动测试时让服务器运行的最佳方法是什么?