GMock - 如何刷新模拟返回值?

时间:2016-03-04 09:17:58

标签: c++ unit-testing googletest googlemock

我有一个类似的测试:

#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();
}

这会崩溃,因为&#34;真实&#34;正在测试的代码会使用DoAllocate两次调用1024。但gmock似乎只做:

Return(malloc(1024))

即使它被召唤两次。显然这是一个问题,因为这意味着malloc用1024调用一次,然后是&#34; real&#34;代码两次释放相同的指针。

如何强制gmock在每次模拟调用时实际执行malloc(1024)

1 个答案:

答案 0 :(得分:1)

通过预先分配缓冲区来设置您的期望,如下所示:

void *buffer1 = malloc(1024);
void *buffer2 = malloc(1024);

EXPECT_CALL(mockIFace, DoAllocate(1024)).Times(2)
    .WillOnce(Return(buffer1))
    .WillOnce(Return(buffer2));