Martin Martin - 1 year ago 165
C++ Question

Adding expected calls in a loop

This is what I want to achieve. In my test fixture I want to call a helper functions with a parameter

to tell the test fixture how many initialization sequences should be expected. Some parameters used in the sequences are stored in three
fileDescriptor, handle, selectionObject

What I have written is this:

void MyTest::init_Ok(uint32_t n)
for (uint32_t i = 0; i < n; ++i)
fileDescriptor.push_back(i); // FDs starting at 0
handle.push_back(reinterpret_cast<void*>(18 + i)); // handles starting at 18
selectionObject.push_back(555 + i); // SOs starting at 555

EXPECT_CALL(MyMockApi::getApi(), initialize(Pointee(nullptr), StrEq("InitString"), MyMatcher()))
EXPECT_CALL(MyMockApi::getApi(), selectionObjectGet(handle[i], Pointee(nullptr)))
EXPECT_CALL(MyMockApi::getApi(), finalize(handle[i]))

I know why it's not working. It is expected that all calls to
will be identical but yet I want to perform different actions (parameter depending on loop counter
) for the first, second, third, ..., nth call. The current implementation will only expect one call to
no matter parameter
. Is it possible to fix this and keep it a loop somehow, or do I have to add the actions with a
line for each
? This would mean i have to check
and add different number of
lines for different possible values of
, which i really want to avoid.

Answer Source

One way could be to use Invoke. You can write a function which will have access to the handles container and a running member/static variable(lets say counterVar) which will indicate the number of times the function is hit. Based on the value of counterVar, you can decide the logic.

.WillRepeatedly(Invoke(<your function>))

Something like:

EXPECT_CALL(MyMockApi::getApi(), initialize(Pointee(nullptr), StrEq("InitString"), MyMatcher()))

ReturnCode successfulInitialize(void* op, std::string msg)
   static int counterVar = 0;
   *op = handles[counterVar++];
   return INIT_OK;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download