[英]Golang HTTP Timeout test, not timing out as expected
I built a small testcase, that checks that code on my end timesout after a set amount of time has passed.我构建了一个小测试用例,它在经过一段时间后检查我的结束超时时的代码。 But this isnt working as expected
但这并没有按预期工作
I am hitting an server sided endpoint which works fine, but what happens if it is slower than usual, I will need code on my end to timeout, this has been implemented but I need to test that I implemented it correctly.我正在访问一个工作正常的服务器端端点,但是如果它比平时慢会发生什么,我需要在我的端代码超时,这已经实现,但我需要测试我是否正确实现了它。
This is what I have so far这是我到目前为止
func TestTimeout(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(time.Second * 15)
}))
defer ts.Close()
client := &http.Client{
Timeout: time.Second * 10,
}
myRequest,err := createMyRequest(Somedata,SomeMoreData)
res, err := client.Do(myRequest)
if err != nil {
t.Fatal(err)
}
res.Body.Close()}
However my code successfully runs without giving a timeout error (as in I am not waiting for 10 seconds, where am I going wrong?但是我的代码成功运行而没有出现超时错误(因为我没有等待 10 秒,我哪里出错了?
As already pointed out in some of the comments, you need to make a request to the test server's endpoint (using ts.URL
) as follows:正如一些评论中已经指出的那样,您需要向测试服务器的端点发出请求(使用
ts.URL
),如下所示:
myRequest, err := http.NewRequest(http.MethodPost, ts.URL, bytes.NewBuffer([]byte("test")))
if err != nil {
t.Fatal(err)
}
res, err := client.Do(myRequest)
if err != nil {
t.Fatal(err)
}
[...]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.