CUnit-'模拟'libc函数 [英] CUnit - 'Mocking' libc functions
问题描述
我正在使用CUnit进行项目单元测试. 我需要测试是否使用正确的参数&调用libc函数.我是否正确地对待了他们的返回值. 例如:如果我调用bind(...)函数-我想检查我通过了&的af参数.断言这是否是错误的,我也想模仿它的返回值&断言我是否以正确的方式进行检查.
I'm using CUnit for my project unit testing. I need to test whether I call libc functions with the right parameters & whether I treat their return values the right way. for example: if I call the bind(...) function - I would like to check which af param I pass & assert if this is the wrong one, and also I would like to emulate it's return value & assert if I check it the right way.
出于这些目的,我希望CUnit环境具有内置的机制,可以让我在测试时调用模拟" bind()函数,在运行代码时调用真实的bind()函数-但我做不到找到这样的东西.
For these purposes I would expect the CUnit environment to have a built-in mechanism to let me call a 'mocked' bind() function while testing and a real bind() function when running the code - but I can't find anything like this.
能否请您告诉我我是否在CUnit中缺少某些内容,或者提出一种实现方法?
Can you please tell me if I'm missing something in CUnit, or maybe suggest a way to implement this.
谢谢, 乔.
推荐答案
不幸的是,您无法使用CUnit在C语言中模拟函数.
Unfortunately, you can't mock functions in C with CUnit.
但是您可以通过使用和滥用define来实现自己的模拟功能: 假设在编译测试时定义UNITTEST,则可以在测试文件(或包含文件)中定义以下内容:
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
在您将在测试模式下编译的mock_helper.c文件中:
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);
}
这篇关于CUnit-'模拟'libc函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!