c++ - CUnit - 'Mocking' libc 函数

标签 c++ c unit-testing cppunit cunit

我正在使用 CUnit 进行项目单元测试。 我需要测试我是否使用正确的参数调用 libc 函数以及我是否以正确的方式处理它们的返回值。 例如:如果我调用 bind(...) 函数 - 我想检查我传递了哪个 af 参数并断言如果这是错误的,我还想模拟它的返回值并断言如果我检查它正确的方法。

出于这些目的,我希望 CUnit 环境有一个内置机制,让我在测试时调用“模拟”bind() 函数,在运行代码时调用真正的 bind() 函数——但我不能找到这样的东西。

如果我遗漏了 CUnit 中的某些内容,您能否告诉我,或者建议一种实现方法。

谢谢, 乔。

最佳答案

不幸的是,您不能使用 CUnit 模拟 C 中的函数。

但是您可以通过使用和滥用定义来实现您自己的模拟函数: 假设您在编译测试时定义了 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);
}

关于c++ - CUnit - 'Mocking' libc 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8339094/

相关文章:

c++ - 将字符串从 std::string 转换为 const char * 时出现数据丢失问题

c++ - 来自类方法的 Cout 不执行任何操作

c:要 float 的字符串(仅适用于 Libc)?

c - int[ ][ ] 和 int** 有什么区别(菜鸟)

c++ - 在 C++ TDD 中调用重载 const 与非 const 方法的好方法?

visual-studio - VS2008 UnitTesting - 与 Office 应用程序对象(PowerPoint 等)分离的 RCW

c++ - 在 SFINAE 中将 int 缩小为 bool,gcc 和 clang 之间的输出不同

c - 使用指针时的奇怪行为

java - EasyMock.expect(...).times(...) 与多次使用 EasyMock.expect(...) 之间的区别?

C++ 错误 : "Array must be initialized with a brace enclosed initializer"