Preferable way to make a unit test with synctest package [closed]

2 weeks ago 9
ARTICLE AD BOX

I have a fire-and-forget goroutine inside my implementation.

go s.httpRepo.HitCallback(request)

The response for that call / hit is ignored, but I need to make sure that it is called exactly once in my unit test.

I can ignore it completely, by not making a mock to httpRepo.hitCallback(), or add Maybe()

s.httpRepo.EXPECT(). HitCallback(mock.Anything). Return(models.MQResponse{ Status: true, }, nil). Maybe() // it is okay if this is not called, but I don't know

Or, using an observer channel.

asyncJobDone := make(chan struct{}) s.httpRepo.EXPECT(). HitCallback(mock.Anything). Return(models.MQResponse{ Status: true, }, nil). Run(func(ctx *fiber.Ctx, request models.MQRequest, headers ...string) { close(asyncJobDone) }). Once() select { case <-asyncJobDone: case <-time.After(3 * time.Second): // timeout after 3 second s.T().Fatal("Timeout: HitCallback was not called") }

Or, using the synctest package.

synctest.Test(s.T(), func(t *testing.T) { s.httpRepo.EXPECT(). HitCallback(mock.Anything). Return(models.MQResponse{ Status: true, }, nil). Once() // just to make sure it's called ONCE synctest.Wait() // is it necessary? })

What is the best practice here (or which one do you recommend the most)? When should I put the synctest.Wait() call?

Read Entire Article