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

拟墨画扇 提交于 2019-12-22 10:27:51

问题


I have a class which accepts a pointer to another class and has a method read():

class B:
{
public:
......
void read(char * str);
......
};

class A
{
public:
A(B *bobj):b(bobj);
B* b;
void read (char * str);
..........
};

I invoke the object like below

A * aobj = new A(new B());

Now I should be able to access read method of both the classes like below:

char text[100];
b->read(text)
aobj->read(text)

The method read of both A and B class is coded to copy some values to the input array as provided.

How can I write MOCK method of the function to modify the argument to a specific value?

ON_CALL(*b, read(::testing::_)).WillByDefault(::testing::Return(outBuffer));

Gives me a compilation issue as read method cannot return a value by definition?


回答1:


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;



}


来源:https://stackoverflow.com/questions/46092758/gmock-how-to-modify-the-method-arguments-when-return-type-is-void

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