GMock - 如何刷新模拟 return 值?
GMock - how to refresh mock return values?
我有一个测试是这样的:
#include <gmock/gmock.h>
using namespace ::testing;
class IMyInterface
{
public:
virtual ~IMyInterface() = default;
virtual void* DoAllocate(size_t size) = 0;
};
class MockMyInterface : public IMyInterface
{
public:
MOCK_METHOD1(DoAllocate, void*(size_t));
};
class InterfaceUser
{
public:
void DoIt(IMyInterface& iface)
{
void* ptr = iface.DoAllocate(1024);
free(ptr);
ptr = iface.DoAllocate(1024);
free(ptr);
}
};
TEST(MyTest, AllocateMock)
{
MockMyInterface mockIFace;
EXPECT_CALL(mockIFace, DoAllocate(1024)).WillRepeatedly(Return(malloc(1024)));
InterfaceUser user;
user.DoIt(mockIFace);
}
int main(int numArgs, char** args)
{
::testing::InitGoogleMock(&numArgs, args);
return RUN_ALL_TESTS();
}
这会崩溃,因为正在测试的 "real" 代码调用 DoAllocate
和 1024
两次。但是 gmock 似乎只做:
Return(malloc(1024))
一次,尽管它被调用了两次。显然这是一个问题,因为这意味着 malloc 被 1024 调用一次,然后 "real" 代码释放同一个指针两次。
如何强制 gmock 在每次模拟调用时实际执行 malloc(1024)
?
通过预分配缓冲区来设置您的期望,如下所示:
void *buffer1 = malloc(1024);
void *buffer2 = malloc(1024);
EXPECT_CALL(mockIFace, DoAllocate(1024)).Times(2)
.WillOnce(Return(buffer1))
.WillOnce(Return(buffer2));
我有一个测试是这样的:
#include <gmock/gmock.h>
using namespace ::testing;
class IMyInterface
{
public:
virtual ~IMyInterface() = default;
virtual void* DoAllocate(size_t size) = 0;
};
class MockMyInterface : public IMyInterface
{
public:
MOCK_METHOD1(DoAllocate, void*(size_t));
};
class InterfaceUser
{
public:
void DoIt(IMyInterface& iface)
{
void* ptr = iface.DoAllocate(1024);
free(ptr);
ptr = iface.DoAllocate(1024);
free(ptr);
}
};
TEST(MyTest, AllocateMock)
{
MockMyInterface mockIFace;
EXPECT_CALL(mockIFace, DoAllocate(1024)).WillRepeatedly(Return(malloc(1024)));
InterfaceUser user;
user.DoIt(mockIFace);
}
int main(int numArgs, char** args)
{
::testing::InitGoogleMock(&numArgs, args);
return RUN_ALL_TESTS();
}
这会崩溃,因为正在测试的 "real" 代码调用 DoAllocate
和 1024
两次。但是 gmock 似乎只做:
Return(malloc(1024))
一次,尽管它被调用了两次。显然这是一个问题,因为这意味着 malloc 被 1024 调用一次,然后 "real" 代码释放同一个指针两次。
如何强制 gmock 在每次模拟调用时实际执行 malloc(1024)
?
通过预分配缓冲区来设置您的期望,如下所示:
void *buffer1 = malloc(1024);
void *buffer2 = malloc(1024);
EXPECT_CALL(mockIFace, DoAllocate(1024)).Times(2)
.WillOnce(Return(buffer1))
.WillOnce(Return(buffer2));