Thank you Zhanyong,
On Dec 30 2008, 2:14 am, Zhanyong Wan (λx.x x) <
w...@google.com>
wrote:
> This technique also works:
>
>
http://code.google.com/p/googlemock/wiki/CookBook#Mocking_Non-virtual...
>
> On Mon, Dec 29, 2008 at 10:09 AM, Zhanyong Wan (λx.x x) <
w...@google.com> wrote:
>
>
>
> > What Chris says would work. My favorite solution is this:
>
> > Instead of calling a free function (say, OpenFile) directly, introduce
> > an abstract class (interface) for it and have a concrete subclass that
> > calls the free functio:
>
> > class FileInterface {
> > public:
> > ...
> > virtual bool Open(const char* path, const char* mode) = 0;
> > };
>
> > class File : public FileInterface {
> > public:
> > ...
> > virtual bool Open(const char* path, const char* mode) {
> > return OpenFile(path, mode);
> > }
> > };
>
> > Your code should talk to FileInterface to open a file. Now it's easy
> > to mock out the function.
>
> > This may seem much hassle, but in practice you often have multiple
> > related functions that you can put in the interface, so the
> > per-function overhead can be much lower.
>
> > On Sat, Dec 27, 2008 at 12:51 PM, Chris Henry <
chrishenry...@gmail.com> wrote:
>
> >> On Sat, Dec 27, 2008 at 6:39 AM, <
yun.y...@gmail.com> wrote:
>
> >>> Hello,
>
> >>> Is it possible to mock C style function using googlemock?
>
> >> I don't have experience with this. But here is my take.
>
> >> Let's talk about the mocking of C functions in general. There are two cases:
>
> >> 1) Calling C function similar to static method:
> >> void doSomething() {
> >> call_this_c_func();
> >> }
> >> in this case call_this_c_func is hard to mock. It is similar to static
> >> methods and is a global name. (If call_this_c_func is in another
> >> library, you can probably dynamically linked a mock library instead of
> >> the real one.)
>
> >> 2) Mocking C function used as function pointer:
> >> void doSomething(void (*func)()) {
> >> func();
> >> }
> >> In this case, it's reasonably easy to mock *func (this is actually
> >> very similar to dependency injection in C++). You can even do this
> >> with C++, just write a mock class with a mock method. Write a function
> >> with similar signature as *func and call the mock method in the mock
> >> class. Pass this function to the function under test (after setting
> >> expectations on the mock method).
>
> >> That's my take. HTH,
>
> >> --
> >> Chris
> >>
chrishenry...@gmail.com