Small utility functions for testing Gin-related code. Such as the creation of a gin context and wait groups with callbacks.
go get github.com/ing-bank/gintestutil
package main
import (
"net/http"
"testing"
"github.com/ing-bank/gintestutil"
)
type TestObject struct {
Name string
}
func TestProductController_Post_CreatesProducts(t *testing.T) {
// Arrange
context, writer := gintestutil.PrepareRequest(t,
gintestutil.WithJsonBody(t, TestObject{Name: "test"}),
gintestutil.WithMethod(http.MethodPost),
gintestutil.WithUrl("https://my-website.com"),
gintestutil.WithHeaders(http.Header{"X-Example": []string{"A", "B"}}),
gintestutil.WithUrlParams(map[string]any{"category": "barbecue"}),
gintestutil.WithQueryParams(map[string]any{"force": "true"}))
// [...]
}
package main
import (
"github.com/stretchr/testify/assert"
"net/http"
"testing"
"github.com/ing-bank/gintestutil"
)
type TestObject struct {
Name string
}
func TestProductController_Index_ReturnsAllProducts(t *testing.T) {
// Arrange
context, writer := gintestutil.PrepareRequest(t)
// [...]
// Assert
var actual []TestObject
if gintestutil.Response(t, &actual, http.StatusOK, writer.Result()) {
assert.Equal(t, []TestObject{}, actual)
}
}
package main
import (
"github.com/gin-gonic/gin"
"github.com/ing-bank/gintestutil"
"net/http"
"net/http/httptest"
"time"
"testing"
)
func TestHelloController(t *testing.T) {
// Arrange
ginContext := gin.Default()
// create expectation
expectation := gintestutil.ExpectCalled(t, ginContext, "/hello-world")
ginContext.GET("/hello-world", func(context *gin.Context) {
context.Status(http.StatusOK)
})
// create webserver
ts := httptest.NewServer(ginContext)
// Send request to webserver path
_, _ = http.Get(fmt.Sprintf("%s/hello-world", ts.URL))
// Wait for expectation in bounded time
if ok := gintestutil.EnsureCompletion(t, expectation); !ok {
// do something
}
}
- Clone the repository
- Run
make tools
to install necessary tools - Run
make t
to run unit tests - Run
make fmt
to format code - Run
make lint
to lint your code
You can run make
to see a list of useful commands.
Nothing here yet!