GMOCK - how to modify the method arguments when return type is void

我怕爱的太早我们不能终老 提交于 2019-12-05 21:41:01

I have used Invoke function to achieve this. Here is a sample code.

If you use >=c++11 then, you can simply give a lambda to the Invoke function.

#include <gtest/gtest.h>                                                                                                                                                                                             
#include <gmock/gmock.h>

using ::testing::Mock;
using ::testing::_;
using ::testing::Invoke;

class actual_reader
{
   public:
   virtual void read(char* data)
   {   
      std::cout << "This should not be called" << std::endl;
   }   
};
void mock_read_function(char* str)
{
   strcpy(str, "Mocked text");
}

class class_under_test
{
   public:
      void read(actual_reader* obj, char *str)
      {   
         obj->read(str);
      }   
};

class mock_reader : public actual_reader
{
   public:
   MOCK_METHOD1(read, void(char* str));
};


TEST(test_class_under_test, test_read)
{
   char text[100];

   mock_reader mock_obj;
   class_under_test cut;

   EXPECT_CALL(mock_obj, read(_)).WillOnce(Invoke(mock_read_function));
   cut.read(&mock_obj, text);
   std::cout << "Output : " << text << std::endl;

   // Lambda example
   EXPECT_CALL(mock_obj, read(_)).WillOnce(Invoke(
            [=](char* str){
               strcpy(str, "Mocked text(lambda)");
            }));
   cut.read(&mock_obj, text);
   std::cout << "Output : " << text << std::endl;



}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!