Using gmock in C code

2,720 views
Skip to first unread message

kumar

unread,
Jun 21, 2014, 9:16:33 PM6/21/14
to googl...@googlegroups.com
Hi,


I am trying to see if it is possible to use gmock on functions written in pure C. I do not want to "mock" the functions really, but be able to assert on the number of times it was called, with what parameters, etc.


Example: [production_code.c]

void outer(void)
{
     inner(1234);
}


I'm calling ``outer()`` from my test case and want to know whether inner( ) was called once, with the value 1234. How to do this? Note that I really want the call to inner() to happen, not just mock it out by an empty implementation.

I looked at the sections "Mocking Free Functions" and "Delegating Calls to a Real Object" in the Cookbook, but both of them assume that the production code is written in C++, not C. I can only write my test code in C++, not production code. What are my options?

Thanks!

Keith Ray

unread,
Jun 30, 2014, 9:50:01 AM6/30/14
to kumar, googl...@googlegroups.com
It would work better if you use CMock or another C-language-based mocking tool. In order to stub or mock a C function, you have to have your test link against a different implementation of that C function. (Or use function pointers.)


One way of using function-pointers is something like this (pseudo C/C++ code):

Instead of this in the header:

void inner(int x);

use this:

typedef void (*InnerFunc)(int x);
extern InnerFunc inner;

In the implementation of inner:

static void inner_impl(int x) { 
... etc..... 
}

InnerFunc inner = inner_impl;

In the test:

static void inner_mock(int x) { 
... etc..... 
}

...blah blah gmock test stuff....

setup() {
save_inner = inner;
inner = inner_mock;
}

teardown()
{
inner = save_inner;
}

test()
{
set expectations for inner_impl
outer();
assert that expectations for inner_impl were satisfied
}

Syntax of the production code remains the same (though now it is actually calling a function-pointer instead of direct reference to the function.)

void outer(void)
{
      inner(1234);
}


This book explains how you can do TDD and mocking in C:


--

---
You received this message because you are subscribed to the Google Groups "Google C++ Mocking Framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to googlemock+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/googlemock/9e86101a-3d0e-4b24-be05-be61080f75f0%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages