I'm currently building a simple API client that will provide a nice wrapper around a remote service's HTTP API. I'm having trouble working out how to mock HTTP responses inside my client, in order to make it easily testable.
For example, take the following example class:
<?php
class ApiClient
{
const API_BASEURL = 'http://ift.tt/1Rs1MXi';
protected $applicationId;
protected $secretKey;
public function __construct($applicationId, $secretKey)
{
$this->applicationId = $applicationId;
$this->secretKey = $secretKey;
}
public function listAccounts()
{
$response = \Httpful\Request::get(self::API_BASEURL.'/accounts')
->expectsJson()
->send();
return $response->accounts;
}
}
I want the developers that are using my client to be able to use it like:
$client = new ApiClient($applicationId, $secretKey);
$accounts = $client->listAccounts();
In practice, this works just fine. But it's really hard for me to unit test the listAccounts() method, because it sends a HTTP request to a hard-coded API_BASEURL. Obviously I don't want my tests to actually fire network calls to a remote service.
I suppose one way around this is to mock the \Httpful\Request class, to make it return a "faked" response instead of actually hitting the network. But how do I pass that mocked class into my listAccounts() method? I can't change its signature to be listAccounts($mockedRequest = null) just for the sake of testing.
What's the best way for me to go about testing this?
Aucun commentaire:
Enregistrer un commentaire