I am using testify
in Go to write unit tests for my service methods and all the methods are working fine excepted the update method because in the update method I call another method("GetByID") of the same service inside the Update method.
Implementation of Update method in my service:
func (ts *teamService) Update(team *team.Team) AppError {
t, err := ts.TeamRepo.GetByID(team.ID)
if err != nil {
return err
}
if t.TeamOwnerID != team.TeamOwnerID {
return NewForbiddenError(forbiddenErr)
}
return ts.TeamRepo.Update(team)
}
MockRepo method for update:
func (t *teamRepoMock) Update(team *team.Team) AppError {
args := t.Called(team)
if args.Error(0) != nil {
return NewNotFoundError(args.Error(0))
}
return nil
}
Implementation of the test:
func TestUpdate(t *testing.T) {
_, teamIdGen, playerIdGen := setupConfig()
t.Run("Update a team", func(t *testing.T) {
teamRepo, _, ts := setupTeamService(teamIdGen, playerIdGen)
teamRepo.On("Update", testTeam1).Return(nil)
result := ts.Update(testTeam1)
assert.Nil(t, result)
})
t.Run("Update a team fails", func(t *testing.T) {
teamRepo, _, ts := setupTeamService(teamIdGen, playerIdGen)
expected := oopsErr
teamRepo.On("Update", testTeam1).Return(expected)
result := ts.Update(testTeam1)
assert.EqualValues(t, expected.Error(), result.Error())
})
}
Now when I run the test I get the following error:
--- FAIL: TestUpdate (0.01s)
--- FAIL: TestUpdate/Update_a_team (0.01s)
panic:
assert: mock: I don't know what to return because the method call was unexpected.
Either do Mock.On("GetByID").Return(...) first, or remove the GetByID() call.
This method was unexpected:
GetByID(string)
0: ""
at: [/home/waleem/Desktop/project/eazykhel_server/services/teamservice/team_service_init_test.go:18 /home/waleem/Desktop/project/eazykhel_server/services/teamservice/team_service.go:146 /home/waleem/Desktop/project/eazykhel_server/services/teamservice/team_service_test.go:277] [recovered]
panic:
I tried calling mock.On("GetByID")
before and after I call .On("Update")
in my test function implementation and it didn't work and also I modified the mockRepo Update function but it didn't work.