Reputation: 35448
I am writing test cases for a scripting language which is embedded in a C (or C++) application and one of the features is that the scripting language calls a method from the "host" program. The entire project is using the google test framework, and down here is one of the tests:
TEST(Functions, ExternalCalling)
{
SCRIPT_START
" \
extern void external_callee(int, int); \
external_callee(1,2); \
"
SCRIPT_END
}
NAP_EXPORTS
void external_callee(nap_int_t a, nap_int_t b)
{
fprintf(stderr, "\na=%"PRINT_d", b=%"PRINT_d"\n", a, b);
if(a != 1 || b != 2) FAIL();
}
Do not mind the SCRIPT_START
and SCRIPT_END
macros, they just create/destroy scripting language objects (NAP_EXPORTS
is defined as extern "C"
so that the dynamic library loader can resolve the name).
As you can see the script defines an external method (from the host application) and then calls it. Right now I am sure that the method is called since I can see on the stderr/output the values of a
and b
but yeah... this has the feeling of manual testing :) How can I use the google test framework to make sure that the method actually was called without having to look on the screen? (I'd like to avoid hackish solutions, like use a global flag...)
Upvotes: 3
Views: 2564
Reputation: 25641
What you actually want to do is mock the function.
Look at mocking frameworks like google-mock.
The EXPECT_CALL
macro lets you specify call occurences (with argument filtering).
See also This SO Question how to create C trampolins to hide C++ interfaces behind C code.
if you also want to have a real result you also might be interested in the invoke
function that allows you to forward arguments to a real implementation.
the google mock cookbook has recipes for all use patterns above.
Upvotes: 3
Reputation: 249552
Here are a few ideas, in order from least to most insidious:
FILE*
parameter to external_callee()
and write there instead of hard-coding stderr
. Then your test harness can hook it up to a temporary file or something fancier.FILE*
to write to. Default it to stderr
but let the test harness change it. Basically like the previous idea but without modifying the signature.printf()
in your test program. Yes, you can probably do this--try it! Just define printf()
yourself with the same signature and that one should get called. Then you can do anything you want.Upvotes: 1