Jo *_* D. 4 c c++ unit-testing cppunit cunit
我正在使用CUnit进行项目单元测试.我需要测试我是否使用正确的参数调用libc函数以及我是否以正确的方式处理它们的返回值.例如:如果我调用bind(...)函数 - 我想检查哪个af param我传递并断言如果这是错误的,并且我想模拟它的返回值并断言如果我检查它正确的方式.
出于这些目的,我希望CUnit环境有一个内置机制让我在测试时调用'mocked'bind()函数,并在运行代码时调用真正的bind()函数 - 但我找不到类似的东西这个.
如果我在CUnit中遗漏了某些东西,或者可能建议一种方法来实现这一点,你能告诉我吗?
谢谢,乔.
不幸的是,您无法使用CUnit在C中模拟函数.
但是您可以通过使用和滥用定义来实现自己的模拟函数:假设您在编译测试时定义UNITTEST,您可以在测试文件(或包含)中定义如下内容:
#ifdef UNITTEST
#define bind mock_bind
#endif
Run Code Online (Sandbox Code Playgroud)
在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;
}
Run Code Online (Sandbox Code Playgroud)
然后,在您的测试文件中:
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);
}
Run Code Online (Sandbox Code Playgroud)