如果标题不清楚很抱歉。
我有一个虚拟基类:
class FileSystemInterface {
public:
virtual ~FileSystemInterface() {};
virtual void save(std::string file_content) = 0;
};我的模拟类是从这个派生出来的:
class MockFile : public FileSystemInterface
{
public:
MOCK_METHOD1(save, void(std::string));
};现在我有了一个测试的方法,它使用一个指向FileSystemInterface的唯一指针
void my_method(std::unique_ptr<FileSystemInterface>& interface)我的测试代码如下:
std::unique_ptr<FileSystemInterface> mockFile(new MockFile);
EXPECT_CALL(*mockFile, save(_));
my_method(mockFile);问题是EXPECT_CALL给了我一个错误class "FileSystemInterface" has no member "gmock_save"
这大概是因为模拟是指向基类的指针,但是如果我按以下方式更改测试:
std::unique_ptr<MockFile> mockFile(new MockFile);
EXPECT_CALL(*mockFile, save(_));
my_method(mockFile);那么EXPECT_CALL很好,但现在my_method抱怨道:a reference of type "std::unique_ptr<FileSystemInterface, std::default_delete<FileSystemInterface>> &" (not const-qualified) cannot be initialized with a value of type "std::unique_ptr<MockFile, std::default_delete<MockFile>>"
我怎样才能避开这场冲突,创造我的测试呢?谢谢。
更新
正如Alexey Guseynov回答中指出的,我的方法确实拥有指针的所有权,所以要做的事情是将我的方法更改为
void my_method(std::unique_ptr<FileSystemInterface> interface);像这样做我的测试:
std::unique_ptr<MockFile> mockFile(new MockFile);
EXPECT_CALL(*mockFile, save(_));
my_method(std::move(mockFile));发布于 2017-05-17 15:27:23
您必须将模拟存储为MockFile,如下所示:
std::unique_ptr<MockFile> mockFile(new MockFile); // not so obvious change
EXPECT_CALL(*mockFile, save(_));
my_method(mockFile);但是您需要更改方法的签名。引用unique_ptr是很奇怪的,因为不清楚谁拥有该对象。如果my_method拥有mockFile,那么通过将指针移动到方法(通过值传递)来传递所有权。如果my_method不拥有该文件,则将其作为普通指针传递。
https://stackoverflow.com/questions/44028922
复制相似问题