Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I stub/mock non-pointer member variables in C++?
    text
    copied!<p>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.</p> <ul> <li>Conditional compilation is allowed.</li> <li>I am specifically using gmock for my stubs/mocks.</li> </ul> <p>Some things that I've researched are:</p> <ul> <li>Using references <ul> <li>involves writing special copy constructors or making it non-copyable</li> <li>still have to manage memory with new/delete</li> <li>not sure if this will cause unforseen problems down the line</li> </ul></li> <li>Creating via code-generation a collection of pointer-wrapper classes. The interface stays the same with a few added methods for testing. <ul> <li>seems like it would work but require upkeep</li> <li>example of what I mean down below</li> </ul></li> </ul> <p><strong>Please note that gmock mock objects are not copyable</strong>, therefore I cannot constructor inject them. (<a href="https://groups.google.com/forum/#!topic/googlemock/GD73UXjQowE/discussion" rel="nofollow">https://groups.google.com/forum/#!topic/googlemock/GD73UXjQowE/discussion</a>)</p> <h1>Problem Example</h1> <pre><code>class Example { public: Example(); ~Example(); private: // I want to stub out _foo. Dependency _foo; }; </code></pre> <h1>Pointer Wrapper Class Example</h1> <pre><code>#ifndef UNIT_TEST Foo _foo; #else PtrWrapFoo _foo; #endif </code></pre> <p><strong>...</strong></p> <pre><code>_foo.setImpl(StubFoo *aStubFoo); </code></pre> <p><strong>...</strong></p> <pre><code>void PtrWrapFoo::doSomething() { _impl-&gt;doSomething(); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload