0

How can I test this function
I need to make sure mocked FindByID function return value is a user with created 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
}

Currently test function

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{})
    })
BigLOL
  • 241
  • 3
  • 9
  • 1
    You can check if the field is empty or not. If you find that insufficient then you could test if it is a valid UUID. And note that if the `ID` field is declared to be of type `uuid.UUID` then the `IsType` test is unnecessary. – mkopriva Jan 12 '21 at 04:45
  • 1
    In Register function, the generated uuid happen earlier than mocked function. In test function, we need to specify FindByID return value. So I can't check its return value if I don't know how to return it – BigLOL Jan 12 '21 at 04:54

1 Answers1

1

As one of options is creating mock manually (if it was generated) to this specific case.

For example (testify-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

kozmo
  • 4,024
  • 3
  • 30
  • 48
  • I'm using https://github.com/vektra/mockery to generate my mock. When I edit manually, vscode give me warning. Also, it'll be a little troublesome if I generating mock again, cause I will always copy this thing. Anyway, it's work. Thank you – BigLOL Jan 17 '21 at 14:04
  • You can contain *specific* `mock` struct in the test package It go s allow you not override this strust when generate `mock` again – kozmo Jan 17 '21 at 14:30