今天看了陈硕(www.chenshuo.com)的一篇blog,有提及单元测试mock系统调用的问题
StackOverFlow网站上有个用户想要mock系统函数getaddinfo,有以下几种方案:
Option 1: Subclass to Test
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; }
};
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.
NOTE: This is quite similar to Patrick's answer but doesn't (hopefully) involve changing the production code if yo