Search code examples
unit-testinggoogletestgooglemock

how to set expect_call on a function in while loop?


I am using gmock, gtest framework to test a function in my code. And I mocked the function which is called in side the main function which is being tested. The mock function is in a infinite while loop and exits only in case of success and keep prints an error message in case of failure. The mocked function looks like this,

while((fd = (socket(_,_,_)) < 0)
 {
   print("error")
 }
  return fd;

now I want to make the socket function fails and prints the error. I managed to print the error but since it's int he while loop it keeps printing the error message. How do I put an expectation so that the gtest stops printing after 1 or 2 times. I put the expectation like this

 EXPECT_CALL(object, socket(_,_,_)).WillRepeatedly(return (error));

I tried with putting .Times(2), but it didn't work.


Solution

  • You'll need to have socket return a value >= 0 if you want the while loop to exit:

    int error(-1), success(0);
    EXPECT_CALL(object, socket(_,_,_))
        .WillOnce(Return(error))
        .WillOnce(Return(error))
        .WillOnce(Return(success));