Reputation: 43
I have a function that is returning the condition of a macro, and for unit testing I want to be able to determine what this macros value is.
Currently I have,
#define READ_PORT ReadingPortStatus(SOME_OTHER_CONDITION)
#ifdef UNIT_TEST
bool READ_PORT_flag_UT;
#endif
void ReturnPortCondition()
{
#ifdef UNIT_TEST
#undef READ_PORT
if (READ_PORT_flag_UT)
{
#define READ_PORT 1
}
else
{
#define READ_PORT 0
}
#endif
if (READ_PORT)
{
return(GOOD_READ);
}
else
{
return(BAD_READ);
}
}
And in my unit test file I would use it as follows,
extern READ_PORT_flag_UT;
READ_PORT_flag_UT = true // Because I want ReturnPortCondition() to return true
bool result = ReturnPortCondition();
However, it is not working as I expect, it is only returning the last define of the port, which in this case is 0. the if else statements are not working in this context.
Upvotes: 0
Views: 1554
Reputation: 7324
Macros are entirely compile time. You can't change a #define
based on a runtime condition.
What you can do instead is re-define READ_PORT
to be your READ_PORT_flag_UT
variable instead of a function call. That way if UNIT_TEST
is defined any use of READ_PORT
will use that variable. If UNIT_TEST
isn't defined READ_PORT
will be the function call.
#ifdef UNIT_TEST
bool READ_PORT_flag_UT;
#define READ_PORT READ_PORT_flag_UT
#else
#define READ_PORT ReadingPortStatus(SOME_OTHER_CONDITION)
#endif
void ReturnPortCondition()
{
if (READ_PORT)
{
return(GOOD_READ);
}
else
{
return(BAD_READ);
}
}
Upvotes: 2