0

我如何测试这个函数
我需要确保模拟的 FindByID 函数返回值是具有创建 UUID 的用户。

func (s *Service) Register(newUser domain.User) (domain.User, error) {
    newUser.ID = uuid.New()
    s.repo.Create(newUser)
    createdUser, err := s.FindByID(newUser.ID)
    if err != nil {
        return domain.User{}, err
    }
    return createdUser, nil
}

目前测试功能

t.Run("When Register called, it should return createdUser", func(t *testing.T) {
        repo := new(mocks.UserRepository)
        s := service.NewService(repo)
        user := domain.User{Name: "TestName", Email: "TestEmail"}

        repo.On("Create", mock.Anything)
        // I need to make sure FindByID function return value is a user with created UUID
        repo.On("FindByID", mock.Anything).Return(user, nil)

        createdUser, err := s.Register(user)

        assert.NoError(t, err)
        assert.IsType(t, createdUser.ID, uuid.UUID{})
    })
4

1 回答 1

1

由于选项之一是mock针对这种特定情况手动创建(如果它是生成的)。

例如(作证模拟):

type repoMock struct {
    mock.Mock
    cache map[uuid.UUID]domain.User
}

func newRepoMock() *repoMock  {
    cache := make(map[uuid.UUID]domain.User)
    return &repoMock{cache: cache}
}

func (m *repoMock) Create(user domain.User) {
    m.Called(user)
    m.cache[user.ID] = user
}

func (m *repoMock) FindByID(uuid uuid.UUID) (domain.User, error) {
    args := m.Called(s)
    res := args[0]
    if res == nil {
        return m.cache[uuid], args.Error(1)
    }
    return res.(domain.User), args.Error(1)
}

PLAYGROUND

于 2021-01-12T07:29:53.690 回答