sinojelly / mockcpp

Two C/C++ testing tools, mockcpp and testngpp.
Apache License 2.0
66 stars 39 forks source link

How can i mock nonvirtual member function? #32

Open git45016683 opened 2 years ago

git45016683 commented 2 years ago

i try to mock a nonvirtual member function, but it show me error like this:

unknown file: Failure
C++ exception with description "Virtual method address should be odd, please make sure the method long (Cfoobar::*)(long) is a virtual method" thrown in the test body.

i want to know below information:

  1. Is mockcpp support mock nonvirtual member function?
  2. if it's support, how can it do that?
// sample code
// mock target class---want to mock nonvirtual function: foobar_l
class Cfoobar {
public:
    Cfoobar() {}
    virtual ~Cfoobar() {}
    long foobar_l(long x) {return x;}
};
// unit test for this class
class CcallCfoobarByobj {
public:
    CcallCfoobarByobj() {}
    virtual ~CcallCfoobarByobj() {}
    Cfoobar cfoobar;
    long callfoobar_l(long x) {return cfoobar.foobar_l(x);}
};
// unit test case
TEST(verifyMockcpp, memberFunctionByObj_Mock) {
    MockObject<Cfoobar> mocker;
    MOCK_METHOD(mocker, foobar_l).stubs().will(returnValue(36));

    CcallCfoobarByobj obj;
    EXPECT_EQ(obj.callfoobar_l(2), 36);
    mocker.verify();
    EXPECT_EQ(obj.callfoobar_l(2), 2);
}
sinojelly commented 2 years ago

You can take a look at this: https://github.com/sinojelly/mockcpp/blob/master/tests/ut/TestNonvirtualMethodMocker.h

Because nonvirtual member function is not interface, maybe mutable, tests depend on it is harmful. So there is no convenient interface to mock nonvirtual member function, just a demo there.

git45016683 commented 2 years ago

Thanks for your response and help. i try to do like the link, but got error " error: ‘CApiHookFunctor’ was not declared in this scope (const void*)CApiHookFunctor<FAKE_BOOST_TYPEOF(Cfoobar::fooWORDref_static)>::hook, ^ " and the same error with 'ThunkCodeProvider'

i search the mockcpp resposity, but didn't found key word 'ThunkCodeProvider' and 'CApiHookFunctor' except this file"https://github.com/sinojelly/mockcpp/blob/master/tests/ut/TestNonvirtualMethodMocker.h"

May I ignore something important? or what's wrong happed?

jhjhuaijie commented 2 years ago

Does mockcpp support virtual functions? It is not pure virtual functions. I try to mock virtual function in class, but return value is not what I expected thank you for your reply.

sinojelly commented 2 years ago

Does mockcpp support virtual functions? It is not pure virtual functions. I try to mock virtual function in class, but return value is not what I expected thank you for your reply.

I think it does.