Test Doubles

You can avoid being blocked, in any of these cases, by employing a test double. A test double is a stand-in—a doppelgänger (literally: “double walker”)—for a production class. HTTP giving you trouble? Create a test double HTTP implementation! The job of the test double will be to support the needs of the test. When a client sends a GET request to the HTTP object, the test double can return a canned response. The test itself determines the response that the test double should return.

Imagine you are on the hook to build the service but you aren’t concerned with unit testing it (perhaps you plan on writing an integration test). You have access to some classes that you can readily reuse.

  • CurlHttp, which uses cURL[15] to make HTTP requests. It derives from the pure virtual base class Http, which defines two functions, get and initialize. Clients must call initialize before they can make calls to get.

  • Address, a struct containing a few fields.

  • AddressExtractor, which populates an Address struct from a JSON[16] string using JsonCpp.[17]

You might code the following:

 
CurlHttp http;
 
http.initialize();
 
auto​ jsonResponse = http.get(createGetRequestUrl(latitude, longitude));
 
 
AddressExtractor extractor;
 
auto​ address = extractor.addressFrom(jsonResponse);
 
 
return​ summaryDescription(address);

Now imagine you want to add tests for that small bit of code. It won’t be so easy, because the CurlHttp class contains unfortunate dependencies you don’t want. Faced with this challenge, many developers would choose to run a few manual tests and move on.

You’re better than that. You’re test-driving! That means you want to add code to your system only in order to make a failing test pass. But how will you write a test that sidesteps the dependency challenges of the CurlHttp class? In the next section, we’ll work through a solution.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.79.241