How to pass timeout while writing test cases in go for httptest

Viewed 26

I am writing test cases for my api ,but its always returning timeout exceeded because it takes bit of time to get data from database ,i want to give explicit timeout in my test cases ,how to do so

func Test_AddHandler(t *testing.T) {
    app := commands.ApiSetup()

    postBody := []byte(`{
   "label":"service153",
   "code":"101333"

}`)

    requestBody := bytes.NewBuffer(postBody)
    req := httptest.NewRequest("POST", "/api/v1/service", requestBody)
    req.Header.Set("Content-Type", "application/json")
    resp, err := app.Test(req)
    utils.AssertEqual(t, nil, err, "app.Test")
    utils.AssertEqual(t, 200, resp.StatusCode, "Status code")
}

The error is receive is test: timeout error 1000ms []

I want to increase this timeout from 1000 ms to higher

I am using go fiber to build my apis

1 Answers
  1. Best way is mock the API response, You can do that by using the Wire Mock (Wire Mock Link: https://wiremock.org/docs/)

or

2. You can try the below one 

func Test_AddHandler(t *testing.T) {
    app := commands.ApiSetup()

    postBody := []byte(`{
   "label":"service153",
   "code":"101333"

}`)

    requestBody := bytes.NewBuffer(postBody)
    req := httptest.NewRequest("POST", "/api/v1/service", requestBody)
    req.Header.Set("Content-Type", "application/json")
    ctx, cancel := context.WithTimeout(context.Background(), 2000*time.Millisecond)
    defer cancel()
    resp, err := app.Test(req.WithContext(ctx))
    utils.AssertEqual(t, nil, err, "app.Test")
    utils.AssertEqual(t, 200, resp.StatusCode, "Status code")
}
Related