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.

273K
  • 29,503
  • 10
  • 41
  • 64

1 Answers1

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.

the busybee
  • 10,755
  • 3
  • 13
  • 30