Adding tests to our shopping list API
Now that we have a clear vision of how tests work, let’s apply it to our project: our API for shopping lists. We’ll start with unit tests, then integration testing, and finally, E2E testing using an HTTP client.
Unit tests
Let’s start by creating a simple unit test. One of the things that we can test in isolation for our application is, for example, the cache middleware. It is a great example of unit tests because it does not require any external dependencies, so it is isolated and doesn’t need any mocks. So, let’s start there:
func TestAddCacheHeaders(t *testing.T) {
testHandler := http.HandlerFunc(func(w http.ResponseWriter,
r *http.Request) {
w.WriteHeader(http.StatusOK)
})
req := httptest.NewRequest("GET", "/lists", nil)
rec := httptest.NewRecorder()
handler := addCacheHeaders(testHandler)
handler(rec, req)
if rec.Header().Get("Cache-Control"...