Testing Custom Context #2158
-
I am looking to test my CustomContext implementations, and running into some issues. Primarily, I am not sure how to set the main.go package main
import (
"net/http"
"github.com/labstack/echo/v4"
)
func main() {
e := echo.New()
e.GET("/", get200, CustomContextMiddleware)
}
func get200(c echo.Context) error {
cc := c.(*CustomContext)
return cc.String(http.StatusOK, "OK")
}
type CustomContext struct {
echo.Context
Custom bool
}
func CustomContextMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
cc := &CustomContext{
Context: c,
Custom: true,
}
return next(cc)
}
} main_test.go package main
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
)
func TestCustomContext (t *testing.T) {
e := echo.New()
e.Use(CustomContextMiddleware)
req := httptest.NewRequest(
http.MethodGet,
"/",
nil,
)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
assert.NoError(t, get200(c))
} This example yields a |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Ehh, its funny how you can stare at something for hours, then as soon as you ask for help, you figure it out...thanks for looking...ill leave this here incase someone else gets confused like i did. package main
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
)
func TestCustomContext(t *testing.T) {
e := echo.New()
e.Use(CustomContextMiddleware)
req := httptest.NewRequest(
http.MethodGet,
"/",
nil,
)
rec := httptest.NewRecorder()
ctx := e.NewContext(req, rec)
c := &CustomContext{
Context: ctx,
Custom: true,
}
assert.NoError(t, get200(c))
} |
Beta Was this translation helpful? Give feedback.
Ehh, its funny how you can stare at something for hours, then as soon as you ask for help, you figure it out...thanks for looking...ill leave this here incase someone else gets confused like i did.