unit-testinggotestify

golang unit test failed Expected nil, but got: "null\n"


First of all i'm trying to learn golang. I tried unit testing my handler in golang as using testify package . When run the my test i got this error -> Expected nil, but got: "null\n" . I was surprised that it showed the value returned from the method as null. As far as I know golangte has nil instead of null. what would be the reason?

my handler test file

package entities

import (
    "github.com/google/uuid"
    "github.com/labstack/echo/v4"
    "github.com/stretchr/testify/assert"
    "net/http"
    "net/http/httptest"
    "strings"
    "testing"
)

type mock struct {
    create  func(user User) error
    getById func(id uuid.UUID) *User
}

var userJson = `{"id":"e918b0bc-76f3-4380-a1fb-a14ca5a08fc3","name":"Jon Snow","email":"jon@jon.com"}`

func (m *mock) Create(user User) error     { return m.create(user) }
func (m *mock) GetById(id uuid.UUID) *User { return m.getById(id) }

func TestCreate(t *testing.T) {
    t.Parallel()
    //Arrange
    e := echo.New()
    expectedStatusCode := http.StatusCreated
    m := &mock{create: func(user User) error { return nil }}
    req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(userJson))
    req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
    rec := httptest.NewRecorder()
    c := e.NewContext(req, rec)
    server := NewUserHandler(m)

    //Act
    server.Create(c)

    //Assert
    assert.Equal(t, expectedStatusCode, rec.Code)
    assert.Nil(t, rec.Body.String())
}


my handler

func (u *userHandler) Create(e echo.Context) error {

    var user User
    err := json.NewDecoder(e.Request().Body).Decode(&user)
    if err != nil {
        e.JSON(http.StatusUnprocessableEntity, err)
    }
    u.userService.Create(user)
    if err != nil {
        e.JSON(http.StatusBadRequest, err)
    }
    return e.JSON(http.StatusCreated, nil)
}

 my user service

 func (u *userService) Create(user User) (err error) {
    err = u.userRepo.Create(user)
    return
}

Solution

  • You're sending back JSON. When you marshal nil, it becomes "null".

    In your test you do

    assert.Nil(t, rec.Body.String())
    

    and rec.Body is the JSON encoded nil (i.e. "null")

    In fact, because rec.Body.String() returns a string, and not *string, this test could never pass.