-2

I have a function say

Myfunction() {  
      x.RunAsync() //Async Function call 
}

I have to write a test case for Myfunction(). I am using go-mock for this. Also have mocked x.

Test_MyFunction() {
   mockCtrl := gomock.NewController(t)
   defer mockCtrl.Finish()
   //EXPECT() call to stub RunAsync()
}

Problem now is my test runs successfully, but somehow at the end it panics saying, that call to mockX.RunAsync() is missing. I think this is because defer is being executed before my RunAsync was stubbed. How do I ensure that all Async functions run before defer is executed.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Arushi
  • 203
  • 1
  • 4
  • 16
  • 1
    This question doesn't really make sense - the only "async function call" in Go is `go `, which doesn't appear in the code shown. And the way to wait for some number of goroutines before continuing execution of some function would be a `sync.WaitGroup`. – Adrian Dec 12 '18 at 21:05
  • `RunAsync()` function implements this, I did not explicitly mention it. – Arushi Dec 12 '18 at 21:13
  • If you've mocked `x` then the mock's `RunAsync` needn't run asynchronously. – Adrian Dec 12 '18 at 21:40

1 Answers1

1

If the test double is being used as a stub, then you should call .AnyTimes() on it. This way gomock won't care if the go routine has finished or not.

If however you are wanting to make assertions on it (and therefore its a mock and not a stub), then you need to ensure the go routine has executed before letting the test finish.

poy
  • 10,063
  • 9
  • 49
  • 74
  • Thanks a ton! Since it is a stub, I can use this. But what if it was otherwise? – Arushi Dec 12 '18 at 21:12
  • 2
    Check out https://medium.com/@poy/gomock-and-go-routines-6a7c01d989d5 for some advice. – poy Dec 12 '18 at 22:31
  • In accordance of your article : What if Bar() returns something. If we put Return() additionally, it shows error. Also if you use DoAndReturn(), then also it says too many argument error. – Arushi Dec 17 '18 at 07:56
  • type Foo interface { Bar (arg1 Arg1, arg2 chan *Arg2) (*ReturnArg, error) } – Arushi Dec 17 '18 at 18:06
  • Sorry I am very new to Go! – Arushi Dec 17 '18 at 18:13
  • so, if I put Do and Return both it says `too many arguments for function call` – Arushi Dec 17 '18 at 18:15
  • File an issue with github.com/golang/mock and we can continue the conversation there (It will be easier to paste code and such). – poy Dec 17 '18 at 18:22
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/185371/discussion-between-arushi-and-poy). – Arushi Dec 17 '18 at 18:28