18
first := mockClient.EXPECT().Do(gomock.Any()).Return(defaultResponse, nil)
mockClient.EXPECT().Do(gomock.Any()).Return(defaultResp, nil).After(first)

How can i call these two mocks one after the other many times ? Is this the correct way to call mocks? I need to execute the first mock first and then the second mockclient. So i have followed this approach. But i need to call them for series of test inputs in my UNIT tests.Where every time the first one should executed first and the second one after that. But i see this is happening for only once and the next time only the second one is called.

Ananth Upadhya
  • 253
  • 1
  • 3
  • 12

1 Answers1

21

The gomock package provides a number methods for ordering.

A note before examples: Using the example you've given, once first is called once, and returns it's values. It will be marked as "used" and "complete", and not considered again.

You will need to set up the expectations again if this has happened.

From the docs:

By default, expected calls are not enforced to run in any particular order. Call order dependency can be enforced by use of InOrder and/or Call.After. Call.After can create more varied call order dependencies, but InOrder is often more convenient.

Link

Two choices for ordering mocks

Ordering of separate mocks:

first := mockClient.EXPECT().Do(gomock.Any()).Return(defaultResponse, nil)
second := mockClient.EXPECT().Do(gomock.Any()).Return(defaultResp, nil)

gomock.InOrder(
    first,
    second,
)

Seeing as the mocks accept exactly the same arguments, you can set up...

Multiple returns on the same mock.

mockClient.EXPECT().
    Do(gomock.Any()).
    Return(defaultResponse, nil).
    Return(defaultResp, nil)
Zak
  • 5,515
  • 21
  • 33
  • 38
    "Multiple returns on the same mock." doesn't work for me. It keep returning the last one for multiple calls – Eric Zheng Jun 03 '20 at 02:55