在 cppunit 测试中存根 WinBase.h

Stubbing WinBase.h in cppunit test

我正在为使用命名管道的 class 编写单元测试。我需要存根 CreateNamedPipe、ConnectNamedPipe、WriteFile、ReadFile、FlushFileBuffers、DisconnectNamedPipe、CloseHandle 和 GetLastError

这些都在WinBase.h中定义为dll导入。

不幸的是 WinBase.h 是一个到处都在使用的巨大文件,因此不能仅仅将要测试的项目存根...

我尝试复制 WinBase.h 并制作函数的内联版本:

bool
ConnectNamedPipe(
    __in        HANDLE hNamedPipe,
    __inout_opt LPOVERLAPPED lpOverlapped
    )
{ return false; }

但是对于每个被覆盖的 function/object 对,我都会得到一个编译错误:

3>test.obj : error LNK2005: ReadFile already defined in main.obj

Main 非常小,但确实包含

#include <file_templates/cppunit/generic_cppunit_main.cpp>

其中可能包含 WinBase.h 某处的深处...

即使我解决了这个编译错误,我也有可能在这个过程中破坏 cppunit?

除了抽象出所有管道调用并存根抽象而不是 WinBase.h 之外,还有什么解决方案吗?

在我看来,通过抽象重定向停止几乎是最好的方法,让您尽可能保持理智。完全使用预处理器可以做到这一点,而且没有运行时开销。只需在 class:

中使用以下设计模式
#ifndef MY_CREATE_NAMED_PIPE
#define MY_CREATE_NAMED_PIPE CreateNamedPipe
#endif

#ifndef MY_CONNECT_NAMED_PIPE
#define MY_CONNECT_NAMED_PIPE ConnectNamedPipe
#endif

...等等。然后,让您的代码使用它们的#defined 别名调用系统调用。

随意使用您喜欢的任何 munging 约定。

然后,在您的单元测试模块中:

#define MY_CREATE_NAMED_PIPE my_create_named_pipe
#define MY_CONNECT_NAMED_PIPE my_connect_named_pipe

// And so on, then include your source module directly:

#include "source.cpp"

您的单元测试模块随后将实施 my_create_named_pipe() 存根等。本质上,您最终将构建一个单独的源模块副本,用于您的单元测试,除了调用的系统调用的名称之外,它在各个方面都是相同的。