I'm writing a library which calls a RESTful API and then performs some work on the data.
I've architected my code like this:
I have a class (let's call it APIRequestor
) that initiates a call to the API via an injected HTTPRequestor
library (which basically wraps a cURL
request). That class, after retrieving the response, will perform some operations on that data and then return an APIResult
object to the caller.
In order to test the APIRequestor
, I created a HTTPRequestorMock
which extends HTTPRequestor
that, rather than wrapping a cURL
request, it simply reads a result from a file I have on disk that way I can test different scenarios.
Below is the code for the APIRequestor
object:
<?php
namespace APITests;
require_once "PHPUnit/Autoload.php";
require_once "../classes/APIRequestor.php";
require_once 'HTTPRequestorMock.php';
class APIRequestor extends \PHPUnit_Framework_TestCase {
public function setUp() {}
public function tearDown() {}
public function getMockedRequestor() {
$requestor = new \APIClasses\APIRequestor();
$requestor->HTTPLibrary = new HTTPRequestorMock();
return $requestor;
}
public function testResponseIDsNoResults() {
$requestor = $this->getMockedRequestor();
$requestor->HTTPLibrary->overrideFilepath = "./mock_assets/ResponseIDsNoResults.xml";
$responseIDs = $requestor->getResponseIDsSinceResponseID(0);
$this->assertTrue(count($responseIDs) === 0, "More than zero results returned.");
}
}
- Is this a good design?
- Can I improve this design in order to make future additions more testable?
- Is this the common practice for removing a dependency on an external server for the sake of my unit tests?
$this->getMock
phpunit thing? \$\endgroup\$