c++ - Unit Testing: coding to interfaces? -
c++ - Unit Testing: coding to interfaces? -
currently project composed of various concrete classes. i'm getting unit testing looks i'm supposed create interface each , every class (effectively doubling number of classes in project)? happen using google mock mocking framework. see google mock cookbook on interfaces. while before might have classes car
, engine
, have abstract classes (aka c++ interfaces) car
, engine
, implementation classes carimplementation
, engineimpl
or whatever. allow me stub out car
's dependency on engine
.
there 2 lines of thought have come across in researching this:
only utilize interfaces when may have need more 1 implementation of given abstraction and/or utilize in public apis, otherwise don't create interfaces unnecessarily.
unit tests stubs/mocks are "other implementation", , so, yes, should create intefaces.
when unit testing, should create interface each class in project? (i'm leaning towards creating interfaces ease of testing)
think you've got number of options. say, 1 alternative create interfaces. have classes
class engine: { public: void start(){ }; }; class auto { public: void start() { // auto specific stuff e_.start(); private: engine e; };
to introduce interfaces - have alter auto take engine
class auto { public: car(engine* engine) : e_(engine) {} void start() { // auto specific stuff e_->start(); private: engine *e_; };
if you've got 1 type of engine - you've made auto objects harder utilize (who creates engines, owns engines). cars have lot of parts - problem go on increase.
if want seperate implementations, way templates. removes need interfaces.
class car<type enginetype = engine> { public: void start() { // auto specific stuff e_.start(); private: enginetype e; };
in mocks, create cars specialised engines:
car<mockengine> testengine;
another, different approach, add together methods engine allow tested, like:
class engine: { public: void start(); bool hasstarted() const; };
you either add together check method car, or inherit auto test.
class testcar : public auto { public: bool hasenginestarted() { homecoming e_.hasstarted(); } };
this require engine changed private protected in auto class.
depending on real world situation, depend on solution best. also, each developer have own holy grail of how believe code should unit tested. personal views maintain client/customer in mind. lets assume clients (perhaps other developers in team) creating cars , don't care engines. hence not want expose concepts of engines (a class internal library) can unit test thing. opt not creating interfaces , testing 2 classes (third alternative gave).
c++ unit-testing interface googlemock concrete
Comments
Post a Comment