gpt4 book ai didi

go - 如何为 go Web api 编写单元测试

转载 作者:数据小太阳 更新时间:2023-10-29 03:46:36 25 4
gpt4 key购买 nike

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

那么如何在记录权限的情况下对这个 API 进行 self 调用?

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)
}
}

关于go - 如何为 go Web api 编写单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44642587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com