3

I am writing Unit test and wondering how would I test function pointers with Cmockery.

A.c

void (*FunctionPtr)(void) = &funcA;

void funcA()
{
  // calls func B 
  funcB();
}

TestA.c

void Test_A( void ** state )
{
   // test for FunA; working as expected
}

void Test_FunctionPtr( void** state )
{
  // how to check here that FunctionPtr holds memory location of funcA?
  // I tried something like below:
  assert_memory_equal( FunctionPtr, funcA(), sizeof( funcA() ) );
}

During runtime I am getting error and I have no clue how to resolve that. May be I using wrong API to assert but don't know which one to call.

Below is my error:

error during runtime:      
Test_FunctionPtr: Starting test
No entries for symbol funcB.
Misha Brukman
  • 12,938
  • 4
  • 61
  • 78
samprat
  • 2,150
  • 8
  • 39
  • 73
  • 4
    "how to check here that FunctionPtr holds memory location of funcA" --> Have you tried `assert(FunctionPtr == funcA);`? Note: best practice to _define_ `funcA()` before using it in `void (*FunctionPtr)(void) = &funcA;` – chux - Reinstate Monica Aug 28 '17 at 17:40
  • 4
    `funcA()` calls the function `funcA`, which returns nothing which cannot be compared. – mch Aug 28 '17 at 17:42
  • @mch Looks almost like an answer. Would you like to make it one? Maybe add a solution, which I think would be using `funcA` instead of `funcA()`. – Yunnosch Aug 28 '17 at 17:45
  • @Yunnosch I think chux has the solution. You want to compare the values of the function pointers, not what it points at. – mch Aug 28 '17 at 17:48
  • After reading comments here , I modified TestA.c to have extern funcA and funcD example extern void funcA() ; extern void funcD(). IN test module I have added assert_int_equal( FunctionPtr , funcA ) and it compiled and test passed. For curiousity I gave assert_int_equal( FunctionPtr, funcD ) and it failed . So i reckon its working – samprat Aug 28 '17 at 17:50
  • True, sorry @chux. Would you like to make an answer? Chm, I think your phrasing was more "attractive". :-) – Yunnosch Aug 28 '17 at 17:50
  • @mch, Your comment was key to this post. Recommend that you post an answer or let OP post a self answer. – chux - Reinstate Monica Aug 28 '17 at 18:07

1 Answers1

2

funcA() calls the function. You want a pointer to the function, which is funcA or &funcA (does not make a difference which one you use: read here).

Also you want to compare the value saved in FunctionPtr with the address of funcA. You do not want to compare the memory where FunctionPtr points to with the function.

So instead of assert_memory_equal( FunctionPtr, funcA(), sizeof( funcA() ) ); I would use assert(FunctionPtr == funcA);

You wrote in your comment that you are using assert_int_equal now. Note that both values are not int, so if the macro uses printf with %d (or similar) in an error case you are invoking undefined behaviour.

mch
  • 9,424
  • 2
  • 28
  • 42