Documentation
¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func NewHttpExpect ¶
NewHttpExpect creates an httpexpect.Expect instance bound directly to the given http.Handler without starting a real HTTP server, suitable for use in unit tests.
Example ¶
ExampleNewHttpExpect demonstrates how to use NewHttpExpect to test an HTTP handler without starting a real server. Copy this pattern into your own _test.go files, passing your test's own *testing.T instead of the placeholder used below.
GET — assert status and a JSON field:
e.GET("/ping").Expect().
Status(http.StatusOK).
JSON().Object().Value("message").String().IsEqual("pong")
POST — send a JSON body and inspect the response:
e.POST("/echo").
WithJSON(map[string]any{"name": "world"}).
Expect().
Status(http.StatusOK).
JSON().Object().Value("data").Object().Value("name").String().IsEqual("world")
This example has no "Output:" comment, so godoc/pkg.go.dev compile it but never execute it — which is why a zero-value *testing.T is enough to stand in below; a real test exercising this exact flow lives in TestNewHttpExpect (httpexpect_test.go).
package main
import (
"net/http"
"testing"
"github.com/gin-gonic/gin"
libtest "github.com/phcp-tech/common-library-golang/test"
)
func main() {
gin.SetMode(gin.TestMode)
router := gin.New()
router.GET("/ping", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "pong"})
})
router.POST("/echo", func(c *gin.Context) {
var body map[string]any
if err := c.ShouldBindJSON(&body); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": body})
})
router.GET("/secret", func(c *gin.Context) {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
})
e := libtest.NewHttpExpect(new(testing.T), router)
// GET — check status code and a JSON string field.
e.GET("/ping").
Expect().
Status(http.StatusOK).
JSON().Object().
Value("message").String().IsEqual("pong")
// POST — send a JSON body; assert a nested response field.
e.POST("/echo").
WithJSON(map[string]any{"name": "world"}).
Expect().
Status(http.StatusOK).
JSON().Object().
Value("data").Object().
Value("name").String().IsEqual("world")
// Error path — assert a non-2xx status code.
e.GET("/secret").
Expect().
Status(http.StatusUnauthorized).
JSON().Object().
Value("error").String().IsEqual("unauthorized")
}
Output:
Types ¶
This section is empty.