I'm trying to mock a simple function from the Linux standard library. strerror() returns the error message from an errno. This is my library with the function to mock:
~$ cat mylib.c
#include <string.h>
#include <stdio.h>
int myStrerror()
{
int error_number = 0;
char* buffer = strerror(error_number);
fprintf(stdout, "Returned string = '%s'\n", buffer);
return 0;
}
#if defined (EXECUTABLE)
int main(int argc, char **argv)
{
return myStrerror();
}
#endif
~$ g++ -pedantic-errors -Wall -c mylib.c
This is my google test:
~$ cat test_mylib.cpp
#include "gtest/gtest.h"
#include "gmock/gmock.h"
int myStrerror();
class strerrorMock {
public:
MOCK_METHOD(char*, strerror, (int));
};
strerrorMock strerrorMockObj;
char *strerror(int error_number) {
return strerrorMockObj.strerror(error_number);
}
TEST(MockTestSuite, strerror)
{
using ::testing::Return;
char response[] = "mocked strerror function";
EXPECT_CALL(strerrorMockObj, strerror(0))
.WillOnce(Return(response));
EXPECT_EQ(myStrerror(), 0);
::testing::Mock::VerifyAndClearExpectations(&strerrorMockObj);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
~$ g++ -pedantic-errors -Wall \
-o test_mylib.a \
-I"$BUILD_DIR"/googletest-src/googletest/include \
-I"$BUILD_DIR"/googletest-src/googlemock/include \
test_mylib.cpp \
"$BUILD_DIR"/lib/libgtestd.a \
"$BUILD_DIR"/lib/libgmockd.a \
./mylib.o \
-lpthread
This is what it returns normally:
~$ ./mylib.a
Returned string = 'Success'
and Running the test gives this:
~$ ./test_mylib.a
[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from MockTestSuite
[ RUN ] MockTestSuite.strerror
Returned string = 'mocked strerror function'
[ OK ] MockTestSuite.strerror (0 ms)
[----------] 1 test from MockTestSuite (0 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test suite ran. (0 ms total)
[ PASSED ] 1 test.
test_mylib.cpp:32: ERROR: this mock object (used in test MockTestSuite.strerror) should be deleted but never is. Its address is @0x56114aa239e0.
ERROR: 1 leaked mock object found at program exit. Expectations on a mock object are verified when the object is destructed. Leaking a mock means that its expectations aren't verified, which is usually a test bug. If you really intend to leak a mock, you can suppress this error using testing::Mock::AllowLeak(mock_object), or you may use a fake or stub instead of a mock.
What have I to do to avoid the memory leak?