CUnit - 'Mocking' libc functions

非 Y 不嫁゛ 提交于 2019-12-05 16:21:29

Unfortunately, you can't mock functions in C with CUnit.

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

#ifdef UNITTEST
    #define bind mock_bind
#endif

In a mock_helper.c file that you will 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 your 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);
}

glibcmock is a solution of mocking libc function with Google Test. for example:

#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));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!