是否有可能,如果可能的话,如何用测试框架控制的定义替换某个定义?
例如,假设嵌入式系统使用定义来访问端口,如下所示:
#define PORTA_CONFIG (*(volatile unsigned int*) (0x1000))
现在,我想确保我的“端口模块”能够正确读取/写入所述 PORTA_CONFIG。我该如何去替换PORTA_CONFIG
类似的东西:
volatile unsigned int PORTA_CONFIG;
对于您使用的生产代码:
//porta_config.h
...
#define PORTA_CONFIG (*(volatile unsigned int*) (0x1000))
在您的测试项目中,您使用另一个标题:
//porta_config_test.h
...
volatile unsigned int PORTA_CONFIG;
如果我正确理解您的意图,您可以执行以下操作:
#define TESTING
int main(){
#ifdef TESTING
volatile unsigned int PORTA_CONFIG;
#else
#define PORTA_CONFIG (*(volatile unsigned int*) (0x1000))
#endif
与 AudioDroid 的答案类似,您可以使用一个“外观标头”包含的不同标头:
portconfig.h包含数据的标头 - 取决于您需要的目标(或者如果您使用它进行测试)
#ifndef PORTCONFIG_H
#define PORTCONFIG_H
#ifdef TARGET_A
# include <portconfig_target_a.h> /* Use the config for target A */
#elif defined TARGET_B
# include <portconfig_target_b.h> /* Use the config for target B */
#elif defined TEST
# include <portconfig_testing.h> /* Use this instead for testing */
#else
# error "Not supported!" /* Just in case ... */
#endif
#endif /* PORTCONFIG_H */
这些头文件中的每一个都包含这些“定义”,因为它们是目标所需要的,例如。
portconfig_target_a.h
...
#define PORTA_CONFIG (*(volatile unsigned int*) (0x1000))
...
或者
portconfig_testing.h
...
volatile unsigned int PORTA_CONFIG;
...
这#ifdef
仅需要一个中心位置,因此维护工作量较小。目标/测试代码的使用也没有区别,#include <portconfig.h>
在所有情况下都使用。
除了PORTA_CONFIG
直接使用,您还可以将其抽象为函数/宏。对于测试,您可以模拟这些。
typedef IOAddress ...
IOData IOData ...
void writePort(IOAddress addr, IOData data);
IOData readPort(IOAddress);
这具有抽象的好处,并且对于测试非常有用。
这个存储库中有一个实现和一些很好的例子,特别是code
(MockIO,header,implementation,example test)——使用 CppUTest。