I’m learning to test http endpoints in Go with the httptest library and my test is failingeven though by the result it should pass.
The function being tested:
func testHandler(w http.ResponseWriter, r *http.Request) {
t := time.Now()
fmt.Fprintln(w, t.YearDay())
}
The test:
func TestTestHandler(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(testHandler))
resp, err := http.Get(server.URL)
if err != nil {
t.Error(err)
}
if resp.StatusCode != http.StatusOK {
t.Errorf("expected 200 but got %d", resp.StatusCode)
}
defer resp.Body.Close()
tme := time.Now()
expected := strconv.Itoa(tme.YearDay())
b, err := io.ReadAll(resp.Body)
if err != nil {
t.Error(err)
}
if string(b) != expected {
t.Errorf("expected %s but got %s", expected, string(b))
}
}
The output:
=== RUN TestTestHandler
testing_http_test.go:31: expected 191 but got 191
--- FAIL: TestTestHandler (0.00s)
i did check that both values are of the same type and they’re both strings, i also tried with hardcoded strings but the test fails either way, so it must be something wrong with the way i’m making the test, though it only gives an error when comparing string(b) != expected
even though they’re the same value and type.
Anyone got a clue?