jueves, 30 de noviembre de 2023

Testear endpoints en go con echo

Supongamos que tenemos unos endpoints hechos con echo:

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) createUser(c echo.Context) error {

    u := new(User)

    if err := c.Bind(u); err != nil {

        return err

    }

    return c.JSON(http.StatusCreated, u)

}


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.StatusOK, user)

}


Lo que queremos hacer es un test de unidad que testee este comportamiento, y podemos hacerlo así: 


package handler


import (

    "net/http"

    "net/http/httptest"

    "strings"

    "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 TestCreateUser(t *testing.T) {

    // Setup

    e := echo.New()

    req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(userJSON))

    req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)

    rec := httptest.NewRecorder()

    c := e.NewContext(req, rec)

    h := &handler{mockDB}


    // Assertions

    if assert.NoError(t, h.createUser(c)) {

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

        assert.Equal(t, userJSON, rec.Body.String())

    }

}


func TestGetUser(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("jon@labstack.com")

    h := &handler{mockDB}


    // Assertions

    if assert.NoError(t, h.getUser(c)) {

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

        assert.Equal(t, userJSON, rec.Body.String())

    }

}


Y listo!! 


Dejo link: https://echo.labstack.com/docs/testing

1 comentario:

  1. I don't understand, what sets this article apart from the linked documentation?

    ResponderBorrar