title: How to mock variadic functions using googlemock
body: <p>Not so much a question as a piece of knowledge sharing.</p>
  <p>According to the GoogleMock <a href="https://github.com/google/googletest/blob/master/docs/gmock_faq.md#can-i-mock-a-variadic-function" rel="nofollow noreferrer">FAQ</a> it is not possible to mock variadic functions since it is unknown how many arguments will be given to the function.</p>
  <p>This is true, but in most cases one knows with how much variables the variadic function is called from the system-under-test or how to transform the variadic arguments to 1 non-variadic argument.<br />
  A colleague of mine (don't know if he is active on Stackoverflow) came up with a working solution as depicted in the example below (using a mock for an C-type interface):</p>
  <pre class="lang-cpp prettyprint-override"><code>    class MockInterface
      {
          public:
              MockInterface() {}
              ~MockInterface() {}
              MOCK_METHOD4( variadicfunction, void( const std:: string name, AN_ENUM mode,
                   const std::string func_name, const std::string message ) );
      };
  
      boost::shard_ptr&lt;MockInterface&gt; mock_interface;
  
      extern &quot;C&quot;
      {
          void variadicfunction( const char *name, AN_ENUM mode,
              const char *func_name, const char *format, ... )
          {
              std::string non_variadic(&quot;&quot;);
  
              if (format != NULL )
              {
                  va_list args;
                  va_start( args, format );
  
                  // Get length of format including arguments
                  int nr = vsnprintf( NULL, 0, format, args );
  
                  char buffer[nr];
                  vsnprintf( buffer, nr+1, format, args );
  
                  non_variadic = std::string( buffer );
  
                  va_end( args );
              }
              
              mock_interface-&gt;variadicfunction( name, mode, func_name, non_variadic );
          }
      }
  </code></pre>
  <p>Hopefully this is useful.</p>