Skip to content

How to test a handler that return 404 ? #593

Description

@remylab

Description

My handler return a 404, but I cannot test the status code returned as the code does not reach my custom ErrorHandler.

Is there any way I can test the actuel status code in my test ?

I would like to test something like that

assert.Equal(t, http.StatusNotFound, rec.Code)

The handler :

func  (h *Handler)Ipsum(c echo.Context) error {

    ipsumMap, err := h.Dbm.GetIpsum( c.Param("uri") )

    // return 404 when there is not match in the DB
    if ( err != nil ) {
        return echo.NewHTTPError(http.StatusNotFound, err.Error())
    }

The test :

func TestIpsum(t *testing.T) {
    dbm, _ := db.NewSqliteManager("./TestIpsum.db")
    defer db.AfterDbTest(dbm,"./TestIpsum.db")()

    test.LoadTestData("./TestIpsum.db","./app_test.TestIpsum.sql")

    h = &Handler{dbm}

    e, req, rec := test.GetEcho(), new(http.Request), httptest.NewRecorder()
    c := e.NewContext(standard.NewRequest(req, e.Logger()), standard.NewResponse(rec, e.Logger()))

    c.SetPath("/:uri")
    c.SetParamNames("uri")
    c.SetParamValues("i-dont-exist")

    assert.Error(t, h.Ipsum(c))
}

Custom ErrorHandler

func ErrorHandler(err error, c echo.Context) {
    code := http.StatusInternalServerError
    msg := http.StatusText(code)
    he, ok := err.(*echo.HTTPError)
    if ok {

        code = he.Code
        msg = he.Message
        fmt.Printf("ErrorHandler msg :%v for URI =%v \n",msg, c.Request().URI())
        switch code {
        case http.StatusNotFound:
            c.Render(code, "404","")
        default:
            c.Render(code, "404",msg)
        }
    }
}

Metadata

Metadata

Assignees

Labels

Type

No type

Fields

No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions