c++cpputest

CppUMock for mocking open() function


Is it possible to mock the C open() function using CppUTest ?

#include "CppUTest/CommandLineTestRunner.h"
#include "CppUTest/TestHarness.h"
#include "CppUTestExt/MockSupport.h"
#include <fcntl.h>

extern "C"
{
#include "drivers/my_driver.h"
}

TEST_GROUP(Driver)
{
    void teardown() {
        mock().clear();
    }
};

int open(const char *__path, int __oflag, ...)
{
    return int(mock().actualCall(__func__)
        .withParameter("__path", __path)
        .withParameter("__oflag", __oflag)
        .returnIntValue());
}

TEST(Driver, simpleTest)
{
    mock().expectOneCall("open")
          .withParameter("/dev/sys/my_hw", O_RDWR)
          .andReturnValue(1);

    mock().checkExpectations();

    bool r = open_driver();
    CHECK_TRUE(r);
}

int main(int ac, char** av)
{
    return CommandLineTestRunner::RunAllTests(ac, av);
}

And here is my open_driver() functions :

#include "drivers/my_driver.h"
#include <string.h>
#include <fcntl.h>

bool open_driver() {
    int fd_driver = open("/dev/iost/mast", O_RDWR);
    char msg[255] = {0};

    if(fd_driver == -1)
        return false;

    return true;
}

For now, I obtain the following error :

/home/.../open_driver.cpp:26: error: Failure in TEST(Driver, simpleTest)
        Mock Failure: Expected call WAS NOT fulfilled.
        EXPECTED calls that WERE NOT fulfilled:
                open -> int /dev/sys/my_hw: <2 (0x2)> (expected 1 call, called 0 times)
        EXPECTED calls that WERE fulfilled:
                <none>

.
Errors (1 failures, 1 tests, 1 ran, 1 checks, 0 ignored, 0 filtered out, 0 ms)

Solution

  • Use compiler option --wrap to handle this scenario. For detail refer below link : How to wrap functions with the `--wrap` option correctly?