如何解决如何模拟在 RAII 类的构造函数中调用的函数
有没有办法使用 Google Mock / Google Test 正确模拟在构造函数中使用的函数调用?这是用于对我的 RAII 类进行单元测试。
我尝试的是创建一个 Mock 类,该类继承自实现并具有 MOCK_METHODx
函数。然后在我的测试套件中,我想在创建对象之前放置 EXPECT_CALL
,但是,对于 EXPECT_CALL
,已经需要创建对象。
// DeviceImpl.h
class DeviceImpl : public IDevice {
public:
explicit DeviceImpl(uint32_t deviceAddress);
~DeviceImpl() override;
uint32_t read();
void write(uint32_t data);
protected:
/* Virtual forwarding functions to make gmock happy */
virtual int _open_device(uint32_t deviceAddress) {
return open_device(deviceAddress); // this is a C function
}
virtual int _close_device(int fd) {
return close_device(fd); // this is a C function
}
}
// DeviceImplMock.h
class DeviceImplMock : public DeviceImpl {
public:
DeviceImplMock() : DeviceImpl(1) {};
~DeviceImplMock() override = default;
MOCK_METHOD1(_open_device,int(uint32_t deviceAddress));
MOCK_METHOD1(_close_device,int(int));
}
// DeviceTest.cc
class DeviceTestSuite : public ::testing::Test {
public:
std::shared_ptr<DeviceImplMock> device_{nullptr};
DeviceTestSuite() {
// Determine how to fix the order problem.
// For the EXPECT_CALL,and thus the mock,the objects already needs to be created.
// However,creating the object (with std::make_shared) already calls the non-mocked function
// What to do here?
EXPECT_CALL(*device_.get(),_open_device(::testing::_)).WillOnce(Return(1));
device_ = std::make_shared<DeviceImplMock>();
}
~DeviceTestSuite() override {
EXPECT_CALL(*device_.get(),_close_device(1)).WillOnce(Return(0));
}
};
TEST_F(DeviceTestSuite,read) {
// Test for device->read() here,etc...
}
非常欢迎有关如何使用 GMock 对 RAII 类进行单元测试的示例。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。