c++ - 使用 boost::shared_ptr 和 AMOP 模拟

标签 c++ boost mocking

我正在尝试使用 amop 编写模拟.我正在使用 Visual Studio 2008。

我有这个接口(interface)类:

struct Interface {
   virtual void Activate() = 0;
};

和接收指向此 Interface 的指针的其他类,如下所示:

struct UserOfInterface {
   void execute(Interface* iface) {
      iface->Activate();
   }
};

所以我试着写一些这样的测试代码:

amop::TMockObject<Interface> mock;
mock.Method(&Interface::Activate).Count(1);

UserOfInterface user;
user.execute((Interface*)mock);

mock.Verifiy();

有效!到目前为止一切顺利,但我真正想要的是 execute() 方法中的 boost::shared_ptr,所以我这样写:

struct UserOfInterface {
   void execute(boost::shared_ptr<Interface> iface) {
      iface->Activate();
   }
};

现在测试代码应该如何?我尝试了一些事情,例如:

amop::TMockObject<Interface> mock;
mock.Method(&Interface::Activate).Count(1);

UserOfInterface user;
boost::shared_ptr<Interface> mockAsPtr((Interface*)mock);
user.execute(mockAsPtr);

mock.Verifiy();

它可以编译,但显然会崩溃,因为在作用域的末尾,变量“mock”被双重销毁(因为堆栈变量“mock”和 shared_ptr)。

我还尝试在堆上创建“模拟”变量:

amop::TMockObject<Interface>* mock(new amop::TMockObject<Interface>);
mock->Method(&Interface::Activate).Count(1);

UserOfInterface user;
boost::shared_ptr<Interface> mockAsPtr((Interface*)*mock);
user.execute(mockAsPtr);

mock->Verifiy();

但它不起作用,不知何故它进入了一个无限循环,在我遇到问题之前,当 shared_ptr 试图删除对象时,boost 找不到模拟对象的析构函数。

有没有人用过amop使用 boost::shared_ptr 成功了吗?

最佳答案

您可能想尝试使用更明确的转换。我不确定这是否有效,但请尝试一下。

// Get the mock generator
boost::shared_ptr< amop::TMockObject<Interface> > mock
    = boost::make_shared< amop::TMockObject<Interface> >;
// Get the mocked interface
boost::shared_ptr<Interface> imock = boost::dynamic_pointer_cast<Interface>(mock);

// Setup mock usage expectations
mock->Method(&Interface::Activate).Count(1);

// Run the test
UserOfInterface user;
user.execute(imock);

// Verify the expectations were met
mock->Verifiy();

关于c++ - 使用 boost::shared_ptr 和 AMOP 模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1633730/

相关文章:

c++ - 使用Qt打印功能

c++ - 如何在 C++ Windows 游戏中播放声音?

c++ - 在 read() 之前检查 boost::asio 缓冲区数据是否存在

c++ - 如何从日期输入方面创建 Boost ptime 对象

python - 用于测试和开发的模拟 python http 请求

java - jMock 模拟类和接口(interface)

c++ - 我能(不能)在 .cpp 文件中包含什么?

c++ - 使用python boost 编译错误

javascript - 为什么在使用 Google Closure 模拟时需要同时调用 replayAll 和 verifyAll?

c++ - 方法 getline c++ 后 Switch 语句 react 错误