Search code examples
c++testinggoogletestgooglemock

How to test with Expect Call on a function that is called within a loop using gmock?


I have a bit of code that sends an HTTPRequest and depending on what the response is, will retry the request a number of times after a short wait.

I have no idea how to mock this out, this is what I have so far

  EXPECT_CALL(*requester, send_request(HttpResponse))
      .Times(1)
      .WillOnce(Return(0));
  HttpResponse response;
  response.status(HTTPSTATUS_NOT_FOUND);
  EXPECT_CALL(*mock_requester, response()).WillOnce(Return(&response)).WillOnce(Return(&response)).WillOnce(Return(&response)).WillOnce(Return(&response));

  EXPECT_THROW(loop_function("hello", true), std::runtime_error);

The actual function is very simple. It attempts to send an HttpRequest, then if it gets back a non 200 response, it will retry up to 3 times. I want to test to make sure it should fail 4 times before throwing an error but gmock is not cooperating (I know the function works, just want to figure out this gmock test)


Solution

  • You can chain multiple WillOnce calls on an expectation, like in this minimal example:

    #include <gmock/gmock.h>
    #include <iostream>
    #include <ostream>
    
    using testing::Return;
    
    class MyMock {
    public:
            MOCK_METHOD0(get_status, int());
    };
    
    int main(void)
    {
            MyMock m;
            EXPECT_CALL(m, get_status())
                    .WillOnce(Return(404))
                    .WillOnce(Return(404))
                    .WillOnce(Return(404))
                    .WillOnce(Return(200));
            for(int i = 0; i < 4; i++)
                    std::cout << m.get_status() << std::endl;
    }