Skip to content

ing-bank/gintestutil

Repository files navigation

🦁 Gin Test Utils

Go package GitHub GitHub go.mod Go version

Small utility functions for testing Gin-related code. Such as the creation of a gin context and wait groups with callbacks.

⬇️ Installation

go get github.com/ing-bank/gintestutil

📋 Usage

Context creation

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"}))

	// [...]
}

Response Assertions

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)
	}
}

Hooks

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
	}
}

🚀 Development

  1. Clone the repository
  2. Run make tools to install necessary tools
  3. Run make t to run unit tests
  4. Run make fmt to format code
  5. Run make lint to lint your code

You can run make to see a list of useful commands.

🔭 Future Plans

Nothing here yet!