Skip to content

httptest recorder always returns 200 HTTP status code in tests with echo  #2491

@yudintsevegor

Description

@yudintsevegor

Issue Description

Hey,
I tried to use the following code as an example for testing echo handlers.

I removed not necessary information from it and added a test case when the status code is different from successful.

Tahnkx in advance!

Checklist

  • [] Dependencies installed
  • No typos
  • Searched existing issues and docs

Expected behaviour

To have a passed test, where rec.Code equals to http.StatusNotFound.

Actual behaviour

Currently, it gets back 200 (OK) when I run go test.

--- FAIL: TestGetUser_NotFound (0.00s)
    handler_test.go:35: 
                Error Trace:    handler_test.go:35
                Error:          Not equal: 
                                expected: 404
                                actual  : 200
                Test:           TestGetUser_NotFound
FAIL
exit status 1
FAIL    examples/echo_examples/tests    0.421s

Steps to reproduce

  • copy code below
  • run go test

Working code to debug

handler.go:

package handler

import (
	"net/http"

	"github.com/labstack/echo/v4"
)

type (
	User struct {
		Name  string `json:"name" form:"name"`
		Email string `json:"email" form:"email"`
	}
	handler struct {
		db map[string]*User
	}
)

func (h *handler) getUser(c echo.Context) error {
	email := c.Param("email")
	user := h.db[email]
	if user == nil {
		return echo.NewHTTPError(http.StatusNotFound, "user not found")
	}

	return c.JSON(http.StatusCreated, user)
}

handler_test.go:

package handler

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/labstack/echo/v4"
	"github.com/stretchr/testify/assert"
)

var (
	mockDB = map[string]*User{
		"jon@labstack.com": &User{"Jon Snow", "jon@labstack.com"},
	}
	userJSON = `{"name":"Jon Snow","email":"jon@labstack.com"}
`
)

func TestGetUser_NotFound(t *testing.T) {
	// Setup
	e := echo.New()
	req := httptest.NewRequest(http.MethodGet, "/", nil)
	rec := httptest.NewRecorder()
	c := e.NewContext(req, rec)
	c.SetPath("/users/:email")
	c.SetParamNames("email")
	c.SetParamValues("unknown@labstack.com")
	h := &handler{mockDB}

	// Assertions
	err := h.getUser(c)
	assert.Error(t, err)

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

}

Version/commit

go version go1.18.2 darwin/amd64

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions