Colonel Panic
Colonel Panic

Reputation: 1614

How can I stub/mock non-pointer member variables in C++?

Many websites on unit testing say to extract an interface and code to the interface (which makes sense), but that requires using polymorphism via pointers. Is it possible to accomplish this without pointers so I don't have to modify the production code? I would rather not use pointers and manage memory.

Some things that I've researched are:

Please note that gmock mock objects are not copyable, therefore I cannot constructor inject them. (https://groups.google.com/forum/#!topic/googlemock/GD73UXjQowE/discussion)

Problem Example

class Example
{
public:
   Example();
   ~Example();

private:
   // I want to stub out _foo.
   Dependency _foo;
};

Pointer Wrapper Class Example

#ifndef UNIT_TEST
   Foo _foo;
#else
   PtrWrapFoo _foo;
#endif

...

_foo.setImpl(StubFoo *aStubFoo);

...

void PtrWrapFoo::doSomething()
{
   _impl->doSomething();
}

Upvotes: 4

Views: 2683

Answers (2)

Colonel Panic
Colonel Panic

Reputation: 1614

After careful consideration, I have decided to abandon the idea. It becomes too difficult to try and manage the circumstances in which the dependency should use a particular implementation (e.g. real, mock, fake), given the testing scenario.

All dependencies that need testing now have interfaces, which are memberless. My production code uses pointers for dependencies, which is a a reality I have to live with if I want testable code. I was persuaded to this notion after reading Roy Osherove's book, The Art of Unit Testing. My regular constructors instantiate the real, concrete class. I also have extra constructors/setters that are conditionally compiled for unit tests so I can properly set up dependencies by using stubs/mocks.

I have reduced my need to write extra code by using a tool to extract an interface from a class.

Overall, the new design is good and adequately sidesteps the problem of mocking non-pointer member variables with minimal overhead.

Upvotes: 2

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

In the past I have implemented Dependency in a separate compilation unit and linked against that instead of the original.

This is what Michael Feathers calls a Link Seam.

Upvotes: 2

Related Questions