0

I have some C++ code where I am calling some C functions from unistd.h such as (open, close, read, write ) etc.. I am trying to mock these functions calls as I do not want to call the actual implementation when running the tests.

I did the following:

Created a Interface:

class InterfaceUnistd
{
    public:
        InterfaceUnistd() {};
        virtual ~InterfaceUnistd() = default;
        virtual int open(const char*, int) = 0;
};

Created a mock:

class UniMock : public InterfaceUnistd
{
    public:
        UniMock() {};
        virtual ~UniMock() {};
        MOCK_METHOD(int, open, (const char*, int), (override));
};

Created a uni_mock.cc file which contains:

#include "uni_mock.hpp"

extern UniMock mockobj;
int open(const char *path, int flags) { return mockobj.open(path, flags); }

I am compiling this as a shared library -luni-mock.so.

In my test file I have:

#include "uni_mock.hpp"
#include "somelib.hpp"

class Foo_Fixture : public ::testing
{
};

TEST_F(Foo, Bar)
{
    uni_mock mock_obj;
    EXPECT_CALL(mock_obj, open("test", _))
        .Times(1)
        .WillOnce(Return(2));

    Fruit apple;
    int ret = apple.init("test"); // init calls open //  
}

When I run the test I get the following error:

status = -1
unittest_sensor_core.cc:230: Failure
Actual function call count doesn't match EXPECT_CALL(mock_obj, open("test", _))...
         Expected: to be called once
           Actual: never called - unsatisfied and active
[  FAILED  ] sensor_core_test_support.GW_start_comm (0 ms)

If I move the mock_obj into global scope the error above goes away but the mock open method is still not called.

I followed the procedure mentioned here to mock c-style function.

3
  • Please look into the method Fruit::init() and count the number of calls of open(). Is it 1 as you expect? -- And please edit your question and provide the full error message, it includes all the details. Commented Jun 17, 2021 at 11:34
  • Yes. Fruit::Init() is calling the open method once. Question updated. Commented Jun 17, 2021 at 13:46
  • Would you mind to provide a minimal reproducible example, please? (Emphasis on minimal and complete.) Commented Jun 28, 2021 at 6:20

1 Answer 1

1

The global extern UniMock mockobj; of your test library in "uni_mock.cc" is another variable than the object uni_mock mock_obj; (typo from re-typing instead of copy-n-paste?) in your test case TEST_F(Foo, Bar).

You might like to look at my answer to a similar question to see a working example.

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

1 Comment

I tried the approach that you mentioned but this is still calling my production code instead of the mock method.

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.