谷歌嘲笑设备

时间:2015-05-04 19:01:45

标签: googlemock

我有一个模拟来模拟从设备读取数据。问题我不知道如何设置buf值来模拟读数。我想模拟sensor.read(buf,sizeof(int))函数中的buf值。有没有办法做到这一点?请看下面的代码:

模拟课程:

class Device
{
 public:
  virtual int Read(char *buf, size_t size) = 0;
};

class MockDevice: public Device{
 public:
  MOCK_METHOD2(Read, int(char *buf, size_t size));
};

我的课程:

class Sensor
{
 private:
   Device *dev;

 public:
  Sensor(Device *device): dev(device);
  int DoRead(char *buf, size_t size){
    dev->Read(buf,size);
    // How can i set the buf here?
  }

}

测试:

TEST(DeviceReadTest, Read)
{
    char buf[10] = {0xAA}
    MockDevice *mockDevice = new MockDevice();

    EXPECT_CALL(*mockDevice, Read(_,_)).Times(1).WillOnce(Return(10));

    Sensor sensor(mockDevice);

    sensor.DoRead(buf,sizeof(buf)); // I wanna pass the buf content to the mock function. Is it possible?
}

1 个答案:

答案 0 :(得分:1)

这样的事情应该有效:

const char read_result[] = "abc";
EXPECT_CALL(*mockDevice, Read(_,_))
    .Times(1)
    .WillOnce(DoAll(
        SetArrayArgument<0>(
            read_result,
            read_result + strlen(read_result)),
        Return(strlen(read_result)));

您可以在https://code.google.com/p/googlemock/wiki/CheatSheet#Actions

找到可能操作的完整列表