mercredi 1 juillet 2015

How to mock function in C when its caller function is defined in same file?

I am trying to mock a function in C, mocking works fine when the function and its caller function are defined in different files. But, when both function(function need to be mocked and its caller) are defined in same file, mocked function is not being invoked.


Case 1 :

//test.c

#include <stdio.h>

/*mocked function*/
int __wrap_func() {
   printf("Mock function !!!\n"); 
}

/*caller function*/
int myTest() {
  return func();
}

int main() {
    myTest();
    return 0;
}

//file.c
#include<stdio.h>

/*function need to be mocked*/
int func() {
  printf("Original function !!!\n");
    }


Case 2 :

//test.c
#include <stdio.h>
extern int myTest();
/*mocked function*/
int __wrap_func() {
  printf("Mock function !!!\n");
}

int main() {
    myTest();
}
//file.c
#include<stdio.h>

/*function need to be mocked*/
int func() {
  printf("Original function !!!\n");
}

/*caller function*/
int myTest() {
  return func();
}


Code compilation command : gcc -Wl,--wrap=func test.c file.c

In Case 1 . Mock function !!!
In Case 2 . Original function !!!

In case 2, mocking function is not being invoked. I am looking for a solution where I can mock function even caller and called function are in same file.

Aucun commentaire:

Enregistrer un commentaire