why C not support TDD. It can't mock function?

115 Views Asked by At

target : mock (main.c) without modified any original file (work.a)

objcopy work.a --add-symbol _real_test1=.text:00000000000126ed,weak --weaken work.a

00000000000126ed is test1 address by command (nm work.a)

override function and call real function in main.c without original file

it can work

#work.a

void test1(){
   printf("old");
}
void test2(){
   test1();
}

#main.c

int real_flag=0;
void test1(){
   if(real_flag){
     _real_test1();
   }else{
     printf("new");
   }
}

int main(){
   test2();//print new
   real_flag=1;
   test2();//print old
}

question : how can I make mutiple real_function

ex: test1,__real_test1 test2,__real_test2...

or other method to mock function

fail to try

fail to try: becuse it need modify original file work.a

void _real_test1() __attribute__((alias("test1")));

fail to try: becuse it just modify function name but not mock function

objcopy --redefine-syms

fail to try: becuse it just work in main.c,it still call old test1 in work.a

gcc -Wl,--wrap=test1
1

There are 1 best solutions below

0
J. Allen On

create mock function override test1 function

  1. command objcopy to make functions of static library weaken
  2. override test1 function in testing program

load real function by shared library

  1. make shared library libfunc.so
  2. dlsym load test1 by function pointer from libfunc.so you can call test1 and __real_test1