我正在尝试使用 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/