0

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)
1
  • 1
    Never used this CppUTest (why not gtest, BTW?), but I don't think so. Your open_driver function is using open directly, so I don't see any way to make it use the mock function (except maybe some hacks with the linker and RTLD_NEXT). Most common way to make your code testable would be passing an interface class to your open_driver and mock this class in your tests. Commented Apr 7, 2022 at 10:40

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.