Testing middleware

Hi,

I am trying to test middleware below but code coverage is always 0 although the test passes. What am I missing?

Thanks

func Timing(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		timer := time.Now()
		next.ServeHTTP(w, r)

		if ID, ok := r.Context().Value("something"); ok {
			log.Info(timer.String())
		}
	}
}
func TestTiming(t *testing.T) {
	timingHandler := func(w http.ResponseWriter, r *http.Request) {
		r.WithContext(context.WithValue(r.Context(), "something", "hello"))
	}

	req := httptest.NewRequest(http.MethodGet, "http://www.example.com", nil)
	res := httptest.NewRecorder()
	timingHandler(res, req)

	tim := Timing(timingHandler)
	tim.ServeHTTP(res, req)

	assert.Equal(t, http.StatusOK, res.Result().StatusCode)
}
1 Like

Sorry, false alarm! The test is actually working fine. Leaving it here just in case if someone needs such thing.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.