jeudi 28 juillet 2016

PHPUnit testing, simulate call to external API

I have a class as follows

class AccountsProcessor{


    protected $remoteAccountData = [];
    /**
     * Process the data passed as an input array
     */
    public function process($inputCsv): array
    {
        $this->loadRemoteData($inputCsv);
        return $this->remoteAccountData;

    }

    /**
     * Given a data retrieved from Local CSV file, iterate each account, retrieve status info from server
     * and save result to instance variable array remoteAccountData
     *
     * @param $inputCsv
     */
    protected function loadRemoteData($inputCsv)
    {
        foreach ($inputCsv as $account)
        {
            // Lookup status data on remote server for this account and add it to RemoteAccountData Array
            $this->remoteAccountData["{$account[0]}"] 
                 = $this->CallApi("GET", "http://ift.tt/2apLHT3]}");
        }
    }

    /**
     * Curl call to Remote server to retrieve missing status data on each account
     *
     * @param $method
     * @param $url
     * @param bool $data
     * @return mixed
     */
    private function CallAPI($method, $url, $data = false)
    {

       ..... internal code ...
    }
}

The class has a public process method which accepts an array and passes it on to a protected function that iterates each account in the array and makes a call to an external API using CURL

My question is this, when I am unit testing this class I just want to test the process method as this is the only public method, the others are private or protected.

I can easily do that like so:

protected $processor;

protected function setUp()
{
    $this->processor = new AccountsProcessor();
}
/** @test */
public function it_works_with_correctly_formatted_data()
{

    $inputCsv = [
        ["12345", "Beedge", "Kevin", "5/24/16"],
        ["8172", "Joe", "Bloggs", "1/1/12"]
    ];

    $processedData = $this->processor->process($inputCsv);
    $this->assertEquals("good", $processedData[0][3]);
}

but running this test actually makes a call to the external API

how can I simulate that call from the private function CallAPI() ?

Aucun commentaire:

Enregistrer un commentaire