2017-03-27 53 views
1

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

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

回答

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;