Question

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.

  • Conditional compilation is allowed.
  • I am specifically using gmock for my stubs/mocks.

Some things that I've researched are:

  • Using references
    • involves writing special copy constructors or making it non-copyable
    • still have to manage memory with new/delete
    • not sure if this will cause unforseen problems down the line
  • Creating via code-generation a collection of pointer-wrapper classes. The interface stays the same with a few added methods for testing.
    • seems like it would work but require upkeep
    • example of what I mean down below

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();
}
Was it helpful?

Solution 2

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top