gin-gonic/website

Testing page not describing tests clearly for more than one route

LucasDSL opened this issue · 0 comments

Situation:

The Testing is not clear enough when we need to test more than one route.

For instance, if we have multiple routes in our project, such as this

func setupRouter() *gin.Engine {
	router := gin.Default()
	router.GET("/albums", getAlbums)
	router.POST("/album", addAlbum)
	router.GET("/albums/:id", getAlbumById)
	return router
}

based on the documentation, how can we test all this routes and also avoid calling setupRouter for every test function? as I did in the project above

func TestGetAlbumsRoute(t *testing.T) {
	router := setupRouter()
	w := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/albums", nil)
	router.ServeHTTP(w, req)

	assert.Equal(t, 200, w.Code)
	assert.Equal(t, "[{\"id\":\"1\",\"title\":\"Blue Train\",\"artist\":\"John Coltrane\",\"price\":56.99},{\"id\":\"2\",\"title\":\"Jeru\",\"artist\":\"Gerry Mulligan\",\"price\":17.99},{\"id\":\"3\",\"title\":\"Sarah Vaughan and Clifford Brown\",\"artist\":\"Sarah Vaughan\",\"price\":39.99}]", w.Body.String())
}

func TestGetAlbumById(t *testing.T) {
	router := setupRouter()
	w := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/albums/2", nil)
	router.ServeHTTP(w, req)

	assert.Equal(t, 200, w.Code)
	assert.JSONEq(t, 
		"{\"id\":\"2\",\"title\":\"Jeru\",\"artist\":\"Gerry Mulligan\",\"price\":17.99}", 
		w.Body.String())
}

The documentation could have just the one example with multiple routes so this scenario would be more wide explained and help more code with basic apis.