Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock malloc to return null in GMOCK?

I want to mock malloc in C++ using Gmock framework. Is it possible? I have tried all possible ways. But the class which is hosting this malloc implementation has got a private constructor and destructor?

Is there any way in which we can directly mock malloc to return NULL?

like image 227
DeveloperLove Avatar asked Jul 15 '13 22:07

DeveloperLove


1 Answers

DeveloperLove,

first of all mocking of standard library is never a good practice and testing the code on such granulation level is art for art's sake. You have to notice that from very beginning, tests become the part of the project and if you want to keep them up-to-date (aka maintaing working regression) you have to think about their design in the same way as production code. In fact tests are also the code which has to be maintained during lifetime of project and if reading, correcting and finnaly understading that tests will take too much time, such regression will be useless. Try to think about it as the "life documentation".

Nevertheless, probably one of the ugliest way to mock the standard C library is static hook and macros. Consider the following example:

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <boost/bind.hpp>
#include <boost/function.hpp>

static boost::function<void*(size_t)> malloc_bridge;

struct StdlibMock
{
    StdlibMock()
    {
        malloc_bridge = boost::bind(&StdlibMock::mallocMock, this, _1);
    }
    MOCK_METHOD1(mallocMock, void*(size_t));
};  // struct Struct StdlibMock

void* malloc_cheat(size_t size)
{
    return malloc_bridge(size);
}

#define malloc malloc_cheat

struct Sut
{
    void f()
    {
        malloc(10);
    }
};

struct TestWithMalloc : ::testing::Test
{
    StdlibMock stdlibMock;
};  // struct TestWithMalloc

TEST_F(TestWithMalloc, ShouldMalloc10Bytes)
{ 
    EXPECT_CALL(stdlibMock, mallocMock(10))
      .WillOnce(::testing::Return(static_cast<void*>(0)));
    Sut sut;
    sut.f();
}

#undef malloc

Notice that you cannot replace the mallocMock function name with simple malloc because of using of preprocessor macro. Hopefully, was a little bit helpful.

like image 84
fttrobin Avatar answered Oct 22 '22 22:10

fttrobin