Error on testing Gingko and Gomega for gingonic, w.Code not working

43 views Asked by At

I have some tests written in Ginkgo that check the return-code, a 502 code should be returned at a specific moment in time, it returns 502 (as you can see on the logs) but the w.Code is still 200.

[GIN] 2024/02/06 - 19:08:01 | 502 |   62.918958ms |                 | PUT      "/v1/create-user"
200

the code that generated that output is the gin router and this fmt.Printf statement:

(test-code)

req, err := http.NewRequest(http.MethodPut, "/v1/create-user", bytes.NewReader(body))
Expect(err).NotTo(HaveOccurred())
req.Header.Set("Content-Type", "application/json")

router.ServeHTTP(w, req)
fmt.Println(w.Code)      // <- this generated the "200"
Ω(w.Code).Should(Equal(502))

as you can see, the request returned 502, but the w.Code still equals 200. Has any one else had this before? Couldn't find aything online.

1

There are 1 answers

0
LombardiD On

Ok, i found some stuff:

But I also found out a solution:

It looks like the "error" is with Go's httptest.ResponseRecorder. It seems that it can only be written once. In my test-suite, the first test is expected to return 200 OK, so it sets that value in the response recorder.

This seemed to fix the issue:

req, err := http.NewRequest(http.MethodPut, "/v1/create-user", bytes.NewReader(body))
Expect(err).NotTo(HaveOccurred())
req.Header.Set("Content-Type", "application/json")

w := httptest.NewRecorder()  // <- creates a new response recorder

router.ServeHTTP(w, req)
Ω(w.Code).Should(Equal(http.StatusBadGateway))

This way the test runs successfully.

Note that i am NOT using gin.CreateTestContext().