golang unit test failed Expected nil,but got:“空\n”

atmip9wb  于 2023-09-28  发布在  Go
关注(0)|答案(1)|浏览(94)

首先,我想学习golang。我尝试在golang中使用testify包对我的处理程序进行单元测试。当运行我的测试时,我得到了这个错误->预期为nil,但得到了:“null\n”。我很惊讶它显示从方法返回的值为null。据我所知,golangte有nil而不是null。是什么原因呢?

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":"[email protected]"}`

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
}
lh80um4z

lh80um4z1#

返回JSON。当你封送nil时,它变成了“null”。
在你的测试中你做了

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

rec.Body是JSON编码的nil(即,“null”)
事实上,因为rec.Body.String()返回的是string,而不是*string,所以这个测试永远不会通过。

相关问题