c++ - How do I use GMock with dependency injection? -


i have class carries couple of dependencies i'd mock using google mocks, in order test class google test.

simplified, have following1:

template<typename tdep> class sut { private:     tdep dependency;  public:     explicit sut(const tdep& dep) : dependency(dep) { }     sut(const sut& other) : dependency(dep.other) { }      // methods use dependency } 

i have interface dependency,

class idependency { public:     virtual double calculatecoolstuff(double) const = 0;     virtual ~idependency() { }; } 

and mock object

class mockdependency { public:     mock_const_method1(calculatecoolstuff, double(double)); }; 

however, when try compile like

mockdependency mock; sut sut(mock); 

i errors stating error: use of deleted function mockdependency(const mockdependency&), i.e. there no copy-constructor of mocked object. found this discussion on google groups ends in making mock objects non-copyable, allowing user add copy constructor , define copy behavior manually. well:

class mockdependency { public:     mockdependency(const mockdependency& other) { }     mock_const_method1(calculatecoolstuff, double(double)); }; 

now code compiles, if run like

mockdependency mock; sut sut(mock);  expect_call(mock, calculatecoolstuff(2.0)).willrepeatedly(return(3.0));  sut.dostuff(); // calls calculatecoolstuff 

in test, error stating call never set up. in other words, instance mock can use setup expectations, no longer same instance on sut used calculations. makes testing gmock , di difficult, least...

what best solution this?


1) yes, i'm using poor man's di. not topic of conversation...

you can use dependency injection references ensuring class member reference:

template<typename tdep> class sut { private:     tdep& dependency;  // reference      // etc. } 

note no longer need copy constructor on mockdependency. rule, need access instances of mock objects being used sut set expectations on them.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -