Self-Initializing Fakes in PHP
Join the DZone community and get the full member experience.
Join For FreeTesting becomes difficult when you consider objects at the boundary of a system: databases, web services, and other integration nightmares. What we usually do is adopting some specialization of the Hexagonal architecture, where the application defines a series of ports where adapters can be plugged into. The internals of the application only depends on the ports interfaces, and not on the actual adapter we use.
How does this architecture simplify testing? It divides your test code into two categories:
- integration tests for the adapters, which are not run very often, and check that the integration with the external resource still works.
- Unit or functional tests for components of the application, which use a Test Double (Stub, Mock, or Fake) in place of the real adapter.
In this article I have to assume you already know by heart the previous paragraph.
The problem
The issue with adapters is that sometimes the mechanism is so complex that you have to use a Fake instead of a simpler Test Double. For example, sqlite in-memory databases instead of the real database is a Fake, since you do not stub the calls to the adapter, but use an alternative, lightweight implementation.
Moreover, writing a Fake is usually very boring and involve saving giant responses. For example, here's a Fake representing an adapter for the Google Maps Directions web service:
<DirectionsResponse> <status>OK</status> <route> <summary>A1</summary> <leg> <step> <travel_mode>DRIVING</travel_mode> <start_location> <lat>45.4636800</lat> <lng>9.1881700</lng> </start_location> <end_location> <lat>45.4604600</lat> <lng>9.1816700</lng> </end_location> ...this goes on and on for some kilobytes
These responses may easily get out of sync with the real ones, but we cannot use the real service for each unit test as it will lower the speed of the tests of an order of magnitude (at least).
The solution
Thus we can specialize our Fake in a Self-Initializing Fake, which will provide an alternative implementation with the aid of the real one. In our Google Maps case, the Fake will use the real web service for its first response, and maintain an internal cache. This mechanism provides insurance about out-of-sync responses, and lets you enjoy the speed of unit tests after the initial warmup: if you always use the same data, no duplicate requests will be made to the external resource.
Example
The purpose of the test developed here is just to test-drive the Self-Initializing Fake and make sure it works, but the tests where you would actually use it are the unit tests of the client code of the adapter. Note also that you'll have to share the same instance of the Fake between tests for the caching to work.
We start with a simple Fake, but we define a stricter tests that say a subsequent identical call should take less than 0.1 times the former one.
<?php class SelfInitializingFakeTest extends PHPUnit_Framework_TestCase { public function testReturnsAlwaysTheSameResultForEachQuery() { $fake = new GoogleMapsDirectionsSelfInitializingFake(); $httpStart = $this->currentTime(); $fake->getDirections('Milan', 'Rome'); $httpEnd = $this->currentTime(); $fake->getDirections('Milan', 'Rome'); $cachedEnd = $this->currentTime(); $httpTime = $httpEnd - $httpStart; $cachedTime = $cachedEnd - $httpEnd; $this->assertGreaterThan(10, $httpTime / $cachedTime); } private function currentTime() { return microtime(true); } } class GoogleMapsDirectionsSelfInitializingFake { public function getDirections($from, $to) { $url = "http://maps.googleapis.com/maps/api/directions/xml?origin={$from}&destination={$to}&sensor=false"; $response = file_get_contents($url); return new SimpleXMLElement($response); } }
Predicatably, the test fails:
[10:08:08][giorgio@Desmond:~]$ phpunit SelfInitializingFakeTest.php PHPUnit 3.5.13 by Sebastian Bergmann. F Time: 1 second, Memory: 3.50Mb There was 1 failure: 1) SelfInitializingFakeTest::testReturnsAlwaysTheSameResultForEachQuery Failed asserting that <double:1.1485217269437> is greater than <integer:10>. /home/giorgio/SelfInitializingFakeTest.php:14 FAILURES! Tests: 1, Assertions: 1, Failures: 1.
By introducing a cache:
class GoogleMapsDirectionsSelfInitializingFake { private $cache = array(); public function getDirections($from, $to) { $url = "http://maps.googleapis.com/maps/api/directions/xml?origin={$from}&destination={$to}&sensor=false"; if (isset($this->cache[$url])) { $response = $this->cache[$url]; } else { $response = file_get_contents($url); $this->cache[$url] = $response; } return new SimpleXMLElement($response); } }
...we make the test pass. Being this a potentially non-deterministic test, involving execution times, I tried it repetedly to catch possible false negatives:
[10:11:20][giorgio@Desmond:~/code/practical-php-testing-patterns]$ phpunit --repeat 100 SelfInitializingFakeTest.php PHPUnit 3.5.13 by Sebastian Bergmann. ................................................................... 67 / 1 (6700%) ................................. Time: 48 seconds, Memory: 3.50Mb OK (100 tests, 100 assertions)
Now we have a Fake that can you save (asymptotically) the same execution time of an independently coded Fake. But it's implemented in 10 lines of code!
Opinions expressed by DZone contributors are their own.
Comments