CUnit - 'Mocking' libc functions

I am using CUnit to test project modules. I need to check if I call libc functions with the correct parameters and correctly handle their return values. for example: if I call the bind (...) function - I would like to check which af param I pass and assert if this is not true, and I would also like to emulate its return value and assert if I check the correct path.

For these purposes, I would expect the CUnit framework to have a built-in mechanism that allows me to call the "mocked" bind () function during testing and the real bind () function when I run the code, but I cannot find anything like that.

Could you tell me if I missed something in CUnit, or maybe offer a way to implement this.

Thanks, Joe.

+4
source share
2 answers

Unfortunately, you cannot simulate functions in C using CUnit.

But you can implement your own mock functions using and abusing definitions: Assuming you define UNITTEST when compiling for tests, you can define something like this in the test file (or in include):

#ifdef UNITTEST #define bind mock_bind #endif 

In the mock_helper.c file that you compile in test mode:

 static int mock_bind_return; // maybe a more complete struct would be usefull here static int mock_bind_sockfd; int mock_bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen) { CU_ASSERT_EQUAL(sockfd, mock_bind_sockfd); return mock_bind_return; } 

Then in the test file:

 extern int mock_bind_return; extern int mock_bind_sockfd; void test_function_with_bind(void) { mock_bind_return = 0; mock_bind_sockfd = 5; function_using_bind(mock_bind_sockfd); } 
+5
source

glibcmock is a mock libc solution with the Google Test . eg:

 #include "got_hook.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include <sys/socket.h> #include <mutex> #include <memory> struct MockBind { MOCK_METHOD3(Bind, int(int, const struct sockaddr*, socklen_t)); }; static MockBind *g_mock{nullptr}; static int Bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen) { return g_mock->Bind(sockfd, addr, addrlen); } static std::mutex g_test_mutex; TEST(BindTest, MockSample) { std::lock_guard<std::mutex> lock(g_test_mutex); std::unique_ptr<MockBind> mock(g_mock = new MockBind()); testing::GotHook got_hook; ASSERT_NO_FATAL_FAILURE(got_hook.MockFunction("bind", (void*)&Bind)); // ... do your test here, for example: struct sockaddr* addr = nullptr; EXPECT_CALL(*g_mock, Bind(1, addr, 20)).WillOnce(testing::Return(0)); EXPECT_EQ(0, bind(1, addr, 20)); } 
0
source

Source: https://habr.com/ru/post/1384073/


All Articles