Test http handlers in go echo

Viewed 78

I am learning go echo and unit test and i am trapped into this and i am here to ask for help.

func TestGetGamesWithTags(t *testing.T){


    req := httptest.NewRequest("http.MethodGet", "/games?tags=tag0", nil)


    //response writer
    // we can inspect the ResponseRecorder output which is response generated by handler 
    recorder := httptest.NewRecorder()
    GlobalTestServer.echo.ServeHTTP(recorder, request)

    // i dont know what to do after this

}

I dont know what to do after

GlobalTestServer.echo.ServeHTTP(recorder, request)
1 Answers

In order to test your echo handlers you need a bunch of things, the echo context, request, recorder, here is an example:

import (
  "net/http"
  "net/http/httptest"
  "net/url"

  "github.com/stretchr/testify/assert"
  "github.com/stretchr/testify/require"
)

func TestGetGamesWithTags(t *testing.T) {
    // Create an instance of Echo.
    e := echo.New() 
    // Create http test recorder
    rec := httptest.NewRecorder()
    // Add url params
    q := make(url.Values)
    q.Set("tags", "tag0")

    req := httptest.NewRequest(http.MethodGet, "/?"+q.Encode(), nil)
    // Create new echo context 
    c := e.NewContext(req, rec) 
    
    // Invoke your handlers against echo context
    assert.NoError(t, getGamesWithTags(c))
  
    require.Equal(t, http.StatusOK, rec.Code)
    assert.JSONEq(
       t,
       `{"key":"value"}`,
       rec.Body.String(),
    )
}
Related