模拟接受 unique_ptr 的方法
MOCK a method that accepts unique_ptr
我有以下 class 需要模拟:
#include <gmock/gmock.h>
#include <gtest/gtest.h>
class Callback
{
public:
Callback(): calls(0)
{}
void mcallback(std::unique_ptr<int> rpely)
{
calls++;
}
uint32_t calls;
};
class MockCallBack : public Callback
{
public:
MOCK_METHOD1(mcallback, void(std::unique_ptr<int>));
};
我遇到以下错误:
error C2280: 'std::unique_ptr<int,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)': attempting to reference a deleted function
1> with
1> [
1> _Ty=int
1> ]
如何模拟相关函数?
您需要执行一些技巧,因为 std::unique_ptr 只是移动 class:
class MockCallBack : public Callback
{
public:
MOCK_METHOD1(mcallbackMock, void(int*));
void mcallback(std::unique_ptr<int> rpely)
{
mcallbackMock(rpely.get())
}
};
那么你可以这样使用它:
MockCallBack mockObject;
auto intPtr = std::make_unique<int>(3)
EXPECT_CALL(mockObject, mcallbackMock(NotNull())); //can use .Times(1) and other things as regular except call
mockObject.mcallback(intPtr); //will trigger except call above
另请查看文档 Mocking Methods That Use Move-Only Types for more examples and more detailed explanation. (It seems that an earlier cookbook 现在已损坏 link。)
A slightly lengthier example can be found in another SO answer 到一个被标记为与该问题重复的问题。 (很难认为标题是重复的,因为一个标题提到了 return 值而另一个提到了函数参数。但是答案中的内容本质上是相同的并且涵盖了两种用例:return 类型和函数参数。)
我有以下 class 需要模拟:
#include <gmock/gmock.h>
#include <gtest/gtest.h>
class Callback
{
public:
Callback(): calls(0)
{}
void mcallback(std::unique_ptr<int> rpely)
{
calls++;
}
uint32_t calls;
};
class MockCallBack : public Callback
{
public:
MOCK_METHOD1(mcallback, void(std::unique_ptr<int>));
};
我遇到以下错误:
error C2280: 'std::unique_ptr<int,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)': attempting to reference a deleted function
1> with
1> [
1> _Ty=int
1> ]
如何模拟相关函数?
您需要执行一些技巧,因为 std::unique_ptr 只是移动 class:
class MockCallBack : public Callback
{
public:
MOCK_METHOD1(mcallbackMock, void(int*));
void mcallback(std::unique_ptr<int> rpely)
{
mcallbackMock(rpely.get())
}
};
那么你可以这样使用它:
MockCallBack mockObject;
auto intPtr = std::make_unique<int>(3)
EXPECT_CALL(mockObject, mcallbackMock(NotNull())); //can use .Times(1) and other things as regular except call
mockObject.mcallback(intPtr); //will trigger except call above
另请查看文档 Mocking Methods That Use Move-Only Types for more examples and more detailed explanation. (It seems that an earlier cookbook 现在已损坏 link。)
A slightly lengthier example can be found in another SO answer 到一个被标记为与该问题重复的问题。 (很难认为标题是重复的,因为一个标题提到了 return 值而另一个提到了函数参数。但是答案中的内容本质上是相同的并且涵盖了两种用例:return 类型和函数参数。)