php - Creating an API client that's unit testable -


i'm building simple api client provide nice wrapper around remote service's http api. i'm having trouble working out how mock http responses inside client, in order make testable.

for example, take following example class:

<?php  class apiclient {     const api_baseurl = 'https://api.someservice.com/v1';      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 developers using client able use like:

$client = new apiclient($applicationid, $secretkey); $accounts = $client->listaccounts(); 

in practice, works fine. it's hard me unit test listaccounts() method, because sends http request hard-coded api_baseurl. don't want tests fire network calls remote service.

i suppose 1 way around mock \httpful\request class, make return "faked" response instead of hitting network. how pass mocked class listaccounts() method? can't change signature listaccounts($mockedrequest = null) sake of testing.

what's best way me go testing this?

normally whould inject request object class (pass via constructor argument) , remove hard dependency. in case, there no request object begin can replace mock. and that's problem static methods. httpful library seems not choice if want write unit tests.

i see 2 options:

  1. use different, more test-friendly library, guzzle
  2. if that's not possible, write thin wrapper, this:

    class httpfulclient {     public function creategetrequest($url)     {         return \httpful\request::get($url);     } } 

    then pass instance of apiclient constructor , mock in tests.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -