title: How to test classes depending on code only defined in header files?
body: <p>I'm getting started with unit testing in C++ and I'm trying to figure out the best practices. Today however I sort of hit a brick wall when writing code that uses <a href="http://www.boost.org/doc/libs/1_53_0/doc/html/interprocess.html" rel="nofollow">boost interprocess</a>, specifically file_mapping and mapped_region which are defined in headers only.</p>
  
  <p>My general question is: How to test classes depending on code only defined in header files (i.e. Boost and STL)?</p>
  
  <p>Example:
  Let's say I create a class like this
  MyClass.h:</p>
  
  <pre><code>#pragma once
  
  #include &lt;stddef&gt;
  
  namespace boost { namespace interprocess {
  class mapped_region;
  }}
  
  class MyClass
  {
  public:
      MyClass(mapped_region&amp; mapped_region);
      std::size_t get_size() const;
  
  private:
      boost::interprocess::mapped_region&amp; mapped_region_;
  }
  </code></pre>
  
  <p>MyClass.cpp file:</p>
  
  <pre><code>#include "MyClass.h"
  #include &lt;boost/interprocess/mapped_region.hpp&gt;
  
  using namespace boost::interprocess;
  
  MyClass::MyClass(mapped_region&amp; mapped_region)
  : mapped_region_(mapped_region) {}
  
  std::size_t MyClass::get_size() const
  {
      return mapped_region_.get_size();
  }
  </code></pre>
  
  <p>How does one go about testing MyClass::get_size()? Since mapped_region implemented in the header file only it will create a object file that is basically independent on other object files (aka, no linking needed) and therefore creating a fake or mock object will not because it cannot be linked in.</p>
  
  <p>The only way I can see working is to use #ifdefs in the .cpp and doing something like this in MyClass.cpp:</p>
  
  <pre><code>#ifdef RUN_UNITTEST
  #include "my_fake_mapped_region.h"
  #else
  #include &lt;boost/interprocess/mapped_region.hpp&gt;
  #endif
  </code></pre>
  
  <p>But this seem like a horrible hack and infects the production code with tests.</p>
  
  <p>I guess one could use boost in the test code, but that would require the creation of files on disk and it would not technically be a unit test anymore, but a integration test? (Sorry if I'm wrong about the terminology).</p>
  
  <p>I would really appreciate some insights on this matter.</p>