Note that there are some explanatory texts on larger screens.

plurals
  1. POMocking an entire library
    primarykey
    data
    text
    <p>I'm developing code that uses <code>boost::asio</code>. To test it, I need to mock a set of classes from this library. I'm using Google Mock, which allows for mocking virtual methods. The usual (and tedious) process would be to write an interface for each of the classes I need to use.</p> <p>On the other hand, the Google Mock Cookbook describes an alternative when it comes to mocking non-virtual methods: using templates. The problem in my case is that I might need to mock several classes at the same time (so using templates directly wouldn't work). So I thought: why not use two-levels of templates? I came up with the following solution:</p> <pre><code>// Classes to be mocked. class RealA { public: void a() { cout &lt;&lt; "RealA::a()" &lt;&lt; endl; }; }; class RealB { public: void b() { cout &lt;&lt; "RealB::b()" &lt;&lt; endl; }; }; // Mock classes. class MockA { public: void a() { cout &lt;&lt; "MockA::a()" &lt;&lt; endl; }; }; class MockB { public: void b() { cout &lt;&lt; "MockB::b()" &lt;&lt; endl; }; }; template&lt;class ABFactory&gt; class Program { public: void setFactory(ABFactory* factory) { factory = factory; } void useA() { typename ABFactory::A* a = factory-&gt;createA(); a-&gt;a(); delete a; } void useB() { typename ABFactory::B b; b.b(); } private: ABFactory* factory; }; template&lt;class ParamA, class ParamB&gt; class TABFactory { public: typedef ParamA A; typedef ParamB B; A* createA() { return new A; }; B* createB() { return new B; }; }; typedef TABFactory&lt;RealA, RealB&gt; RealABFactory; typedef TABFactory&lt;MockA, MockB&gt; MockABFactory; </code></pre> <p>Then, the normal usage would be:</p> <pre><code>Program&lt;RealABFactory&gt; p; p.useA(); p.useB(); </code></pre> <p>While the test would be:</p> <pre><code>Program&lt;MockABFactory&gt; t; t.useA(); t.useB(); </code></pre> <p>This starts to get complicated when the mocked classes have methods with complex parameters (such as other classes from the same library which might not be mocked). In summary, it doesn't seem to scale. Any thoughts on this solution, or suggestions on other approaches to the problem?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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