Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In this case you don't need to mock <code>getaddrinfo</code>, rather, you need to test without relying on its functionality. Both Patrick and Noah have good points but you have at least two other options:</p> <h2>Option 1: Subclass to Test</h2> <p>Since you already have your object in a class, you can subclass to test. For example, assume the following is your actual class:</p> <pre><code>class DnsClass { int lookup(...); }; int DnsClass::lookup(...) { return getaddrinfo(...); } </code></pre> <p>Then, for testing, you would subclass like this:</p> <pre><code>class FailingDnsClass { int lookup(...) { return 42; } }; </code></pre> <p>You can now use the <code>FailingDnsClass</code> subclass to generate errors but still verify that everything behaves correctly when an error condition occurs. Dependency Injection is often your friend in this case.</p> <p>NOTE: This is quite similar to Patrick's answer but doesn't (hopefully) involve changing the production code if you aren't already setup for dependency injection.</p> <h2>Option 2: Use a link seam</h2> <p>In C++, you also have link-time seams which Michael Feathers describes in <a href="http://rads.stackoverflow.com/amzn/click/0131177052" rel="noreferrer"><em>Working Effectively with Legacy Code</em></a>.</p> <p>The basic idea is to leverage the linker and your build system. When compiling the unit tests, link in your own version of <code>getaddrinfo</code> which will take precedence over the system version. For example:</p> <p>test.cpp:</p> <pre><code>#include &lt;sys/types.h&gt; #include &lt;sys/socket.h&gt; #include &lt;netdb.h&gt; #include &lt;iostream&gt; int main(void) { int retval = getaddrinfo(NULL, NULL, NULL, NULL); std::cout &lt;&lt; "RV:" &lt;&lt; retval &lt;&lt; std::endl; return retval; } </code></pre> <p>lib.cpp:</p> <pre><code>#include &lt;sys/types.h&gt; #include &lt;sys/socket.h&gt; #include &lt;netdb.h&gt; int getaddrinfo(const char *node, const char *service, const struct addrinfo *hints, struct addrinfo **res ) { return 42; } </code></pre> <p>And then for testing:</p> <pre><code>$ g++ test.cpp lib.cpp -o test $ ./test RV:42 </code></pre>
    singulars
    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.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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