1

我正在编写一个单元测试(在cpputest中),我尝试对函数调用执行“依赖注入”。这意味着当单元测试必须调用放置在被测文件中的真实函数时,函数调用应该重定向到“假”实现。实际上我将函数指针分配给真正的函数并用“假实现”覆盖它。它的构造如下:

============ myfile.h =========================
 int8 my_function_FAKE (int8 address)     // Declaration of my_function_FAKE
==============================================

================= myfile.c ====================
#include "myfile.h"

static int8 my_function (int8 address)   // The original function
{
   return value;
}


#IF DEFINED (UNIT_TEST)
int8 my_function_FAKE (int8 address)   // the "fake" of the original function 
{
   switch (address)
   {
      case 10: return 11
      case 20: return 21
      case 30: return 31
   }
}
#ENDIF

======================TEST ENVIRONMENT =======================
==============================================================

========FAKE.h===============
extern int8(*Function)(int8);
=========================

 ========FAKE.c==========
 #include "myfile.h"
 #include "FAKE.h"

 int8 (*Function)(int8) = my_function;
 =========================

=======Unit Test File======
Function = my_function_FAKE; // Injecting the fake implementation within unit test file
===========================

我收到编译器错误:

FAKE.c: error C2065: 'my_function' : undeclared identifier
FAKE.c: error C2099: 'my_function' : initializer is not a constant 

我已经尝试了一些组合,但每次都出现相同的错误。解决方案可能很简单,但我忽略了它。那么,我在这里做错了什么?

4

1 回答 1

0

我发现您的代码存在更多问题:

  1. my_function是一个静态函数,因此您无法从另一个编译单元访问(您应该将其声明修改为非静态)

  2. int8 (*Function)(int8)是一个函数指针声明,所以你需要my_function. 您的代码 ( FAKE.c) 应类似于以下内容:

     extern int8 my_function (int8 address);
     int8 (*Function)(int8) = &my_function;
    
  3. 同样在您的单元测试中,您应该使用 my_function_FAKE 的地址:

     Function = &my_function_FAKE;
    
于 2017-10-17T13:12:37.913 回答