CUnit - 'Mocking' libc 函数
CUnit - 'Mocking' libc functions
我使用CUnit进行项目单元测试。我需要测试是否使用正确的参数调用libc函数&是否以正确的方式处理它们的返回值。例如:如果我调用bind(…)函数-我想检查我传递了哪个af参数&断言如果这是错误的,我也想模仿它的返回值&
出于这些目的,我希望CUnit环境有一个内置机制,让我在测试时调用"模拟"bind()函数,在运行代码时调用真正的bind()函数,但我找不到这样的东西。
你能告诉我,如果我错过了什么在CUnit,或者建议一个方法来实现这一点。
谢谢,乔。
不幸的是,你不能用CUnit模拟C中的函数。
但是你可以通过使用和滥用定义来实现你自己的mock函数:假设您在编译测试时定义了UNITTEST,那么您可以在被测试的文件(或包含文件)中定义如下内容:
#ifdef UNITTEST
#define bind mock_bind
#endif
在测试模式下编译的mock_helper.c文件中:
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;
}
然后,在您的测试文件中:
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是一个使用Google Test模拟libc函数的解决方案。例如:
#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));
}
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 如何修复Mac上的clang-libc++错误:调用私有构造函数
- LIBC的mktime函数对于相同的输入返回不同的值
- CUnit - 'Mocking' libc 函数
- 为什么libstdc++和libc++都不检查默认的unique_ptr构造函数的指针和引用类型D ?
- libstdc++和libc++在用lambda构造std::函数时的不同行为
- 在使用std::copy而不是std::memcpy复制字符时避免libc函数调用