httptest

Makes http testing easier

Go
Coverage Status

Install

go get github.com/gmvbr/httptest

Request

Create request for testing

New

rb := httptest.New("/path", "GET")

GET

rb := httptest.Get("/path")

HEAD

rb := httptest.Head("/path")

POST

rb := httptest.Post("/path")

PUT

rb := httptest.Put("/path")

DELETE

rb := httptest.Delete("/path")

CONNECT

rb := httptest.Connect("/path")

OPTIONS

rb := httptest.Options("/path")

TRACE

rb := httptest.Trace("/path")

PATCH

rb := httptest.Patch("/path")

Params

rb.Param("key", "value)

Headers

rb.Header("key", "value)

Body

Send string

rb.String("Hello world")

Send json

type Message {
    Title       string `json:"title"`
    Description string `json:"title"`
}

rb.Json(&Message{Title: "Hello", Description: "Hello World"})

Cookies

rb.Cookie(&http.Cookie{
    Name: "Cookie Name", 
    Value: "Cookie Value",
})

Build request

req := rb.Request()

Example

req := httptest.Get("/").String("Hello world").Request()

Response

Create test

test := httptest.NewTest(testing.T, http.Response)

Expect statusCode

test.Status(expectedCode)

Expect header value

test.Header(headerKey, headerValue)

Expect body string

test.Body(expectedString)

Expect body json

test.Json(expected)

Expect cookie

test.Cookie(&http.Cookie{
    Name:     "Cookie Name",
    Value:    "Cookie Value",
    Path:     "/",
    SameSite: http.SameSiteLaxMode,
})

Test gofiber app

import (
	"testing"

	"github.com/gofiber/fiber/v2"
	"github.com/gmvbr/httptest"
)

type Message {
    Title       string `json:"title"`
    Description string `json:"title"`
}

func TestHandler(t *testing.T) {
    app := fiber.New()

    app.Get("/", func(c *fiber.Ctx) error {
        return c.SendString("Hello, World 👋!")
    })

    app.Post("/message", func(c *fiber.Ctx) error {
        body := &Message{}
		if err := c.BodyParser(body); err != nil {
			return c.SendStatus(fiber.StatusBadRequest)
		}
		return c.JSON(body)
    })

    // test /
    test := httptest.Get("/").Test(t, app)
    test.Status(200)
    test.Body("Hello, World 👋!")

    // test /message
    rb := httptest.Post("/message")
    rb.Json(&Message{Title: "Hello", Description: "Hello World"})

    test := rb.Test(t, app)
    test.Status(200)
    test.Json(&Message{Title: "Hello", Description: "Hello World"})
}

GitHub

View Github