Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking same functions with different response many times one after the other in Go lang

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.

like image 561
Ananth Upadhya Avatar asked Sep 12 '25 06:09

Ananth Upadhya


1 Answers

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.

Edit: reported not to be working by some commenters

mockClient.EXPECT().
    Do(gomock.Any()).
    Return(defaultResponse, nil).
    Return(defaultResp, nil)
like image 164
Zak Avatar answered Sep 13 '25 19:09

Zak