Advice on Mocking System Calls(关于模拟系统调用的建议)
问题描述
我有一个类调用 getaddrinfo 进行 DNS 查找.在测试期间,我想模拟涉及此系统调用的各种错误情况.像这样模拟系统调用的推荐方法是什么?我正在使用 Boost.Test 进行单元测试.
I have a class which calls getaddrinfo for DNS look ups. During testing I want to simulate various error conditions involving this system call. What's the recommended method for mocking system calls like this? I'm using Boost.Test for my unit testing.
推荐答案
在这种情况下,您不需要模拟 getaddrinfo
,而是需要在不依赖其功能的情况下进行测试.帕特里克和诺亚都有优点,但你至少还有两个选择:
In this case you don't need to mock getaddrinfo
, rather, you need to test without relying on its functionality. Both Patrick and Noah have good points but you have at least two other options:
由于您已经在一个类中拥有您的对象,您可以创建子类进行测试.例如,假设以下是您的实际课程:
Since you already have your object in a class, you can subclass to test. For example, assume the following is your actual class:
class DnsClass {
int lookup(...);
};
int DnsClass::lookup(...) {
return getaddrinfo(...);
}
然后,为了测试,你可以这样子类化:
Then, for testing, you would subclass like this:
class FailingDnsClass {
int lookup(...) { return 42; }
};
您现在可以使用 FailingDnsClass
子类来生成错误,但在发生错误情况时仍然可以验证一切行为是否正确.在这种情况下,依赖注入通常是您的朋友.
You can now use the FailingDnsClass
subclass to generate errors but still verify that everything behaves correctly when an error condition occurs. Dependency Injection is often your friend in this case.
注意:这与 Patrick 的回答非常相似,但如果您尚未设置依赖注入,则不(希望)涉及更改生产代码.
NOTE: This is quite similar to Patrick's answer but doesn't (hopefully) involve changing the production code if you aren't already setup for dependency injection.
在 C++ 中,您还拥有 Michael Feathers 在 有效地使用遗留代码.
In C++, you also have link-time seams which Michael Feathers describes in Working Effectively with Legacy Code.
基本思想是利用链接器和构建系统.编译单元测试时,链接您自己的 getaddrinfo
版本,该版本将优先于系统版本.例如:
The basic idea is to leverage the linker and your build system. When compiling the unit tests, link in your own version of getaddrinfo
which will take precedence over the system version. For example:
test.cpp:
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <iostream>
int main(void)
{
int retval = getaddrinfo(NULL, NULL, NULL, NULL);
std::cout << "RV:" << retval << std::endl;
return retval;
}
lib.cpp:
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
int getaddrinfo(const char *node, const char *service,
const struct addrinfo *hints, struct addrinfo **res
)
{
return 42;
}
然后进行测试:
$ g++ test.cpp lib.cpp -o test
$ ./test
RV:42
这篇关于关于模拟系统调用的建议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:关于模拟系统调用的建议
基础教程推荐
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 设计字符串本地化的最佳方法 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01