1

I'm writing an Unit Test (in cpputest) where I try to perform an "dependence injection" to a function call. This means when the Unit Test have to call the real function which is placed within the file under test, the function call should be redirected to a "fake" implementation. Actually I'm assigning function pointer to the real function and overwriting it with the "fake implementation". It's constructed as follow:

============ 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
===========================

I'm getting the compiler error:

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

I tried already some combinations but each time the same error. The solution is maybe simple, but I'm overlooking it. So, what I'm doing wrong here?

JohnDoe
  • 825
  • 1
  • 13
  • 31

1 Answers1

0

I see more problems with your code:

  1. my_function is a static function therefore you can't reach from another compilation unit (you should modify its declaration to non-static)

  2. int8 (*Function)(int8) is a function pointer declaration so you need the address of the my_function. Your code (FAKE.c) should look like something similar:

     extern int8 my_function (int8 address);
     int8 (*Function)(int8) = &my_function;
    
  3. Also in your unit test you should use the address of my_function_FAKE:

     Function = &my_function_FAKE;
    
Ricardo Rocha
  • 14,612
  • 20
  • 74
  • 130