c++ - GMock passing a mocked object into another, and calling a stubed method is still calling real logic -
i'm trying pass mocked object object's method , call it, same result call real method.
fooa.h - real class
#ifndef fooa_h #define fooa_h class fooa { public: fooa(); virtual int method(int a, int b, int c, int d); }; #endif // fooa_h
fooa.cpp
#include "fooa.h" fooa::fooa() { } int fooa::method(int a, int b, int c, int d) { return a+b+c+d; }
mockedfooa.h - mocked version of fooa
#ifndef mockedfooa_h #define mockedfooa_h #include "fooa.h" #include <gmock/gmock.h> class mockedfooa : public fooa { public: mock_method4( method, int(int a, int b, int c, int d) ); }; #endif // mockedfooa_h
calculator.h class invokes method fooa class
#include "fooa.h" #include <iostream> class calculator { public: calculator() { } void docalc(fooa foo) { int = 3, b =4 ,c = 12, d = 41; std::cout<<foo.method(a,b,c,d)<<std::endl; } };
and main function
#include "mockedfooa.h" #include "calc.h" using ::testing::_; using ::testing::return; using namespace std; int main(int argc, char *argv[]) { calculator ocalc; // object uses ofoo.method fooa ofoo;//not mocked ocalc.docalc(ofoo); mockedfooa omockedfoo ; // mocked on_call(omockedfoo,method(_,_,_,_)).willbydefault(return(20)); ocalc.docalc(omockedfoo); }
the output is
60 60
so looks though stubbed docalc still invokes real method.
and question is: why when i'm passing mocked object docalc method isn't calling stubbed method?
the problem you're passing mocked object value. since mock objects exploit dynamic binding provided inheritance, need pass them around using references or pointers. otherwise you'll end slicing objects.
to achieve desired behavior, change docalc
method take fooa
parameter by-reference instead of by-value. this:
void docalc(fooa& foo)
Comments
Post a Comment