lundi 1 février 2016

Not understanding mocking in php or in guzzel.

Looking for some help here. Consider the following class:

class Details {

    public function details($href) {
        $client = new Client();

        $response = $client->request('GET', $href);
        EveLogHandler::requestLog($response, 'eveonline_item_details.log');

        if ($response->getStatusCode() === 200) {
            return json_decode($response->getBody()->getContents());
        }

        return false;
    }
}

Pretty basic, we create a client, send a GET request to the href, log the response, then do stuff on status code of 200 or return false.

What I dont get is the following:

  1. How do you test this with out hitting the API?
  2. How do you mock the client objects as demonstrated here inside a class method
  3. What if this was a pool? How would you mock a pool? see example bellow:

In this example for Pool I have a method inside of a different class that uses the pool concept:

public function fetchGroupsInfromation(array $groups) {
    $groupInformationContainer = [];

    $createdRequests           = [];
    $acceptedResponses         = [];
    $rejectedResponses         = [];

    $client                    = new Client();

    foreach($groups as $group) {
        array_push($createdRequests, new Request('GET', $group->types->href));
    }

    $pool = new Pool($client, $createdRequests, [
        'concurrency' => 10,
        'fulfilled'   => function ($response, $index) use (&$acceptedResponses) {
            EveLogHandler::requestLog($response, 'eve_online_group_items_responses.log');

            $groupPagesItterator = new GroupPagesItterator(json_decode($response->getBody()->getContents()));
            $acceptedResponses[$index] = iterator_to_array($groupPagesItterator->getAllPages());
        },
        'rejected'    => function ($reason, $index) use(&$rejectedResponses)  {
            array_push($rejectedResponses, $reason);
        },
    ]);

    $promise = $pool->promise();
    $promise->wait();
}

I took out some of the other logic inside this method because the main thing I need help with is understanding how to write tests for class methods like these where they use third party services.

The goal is to never hit the API, I have a couple controller tests further up that do that for me (integration tests if you will) How ever I need to test code like this to make sure I get back what I expect. But I feel that if I mock the method or the code inside the method that at that point I am just "spell checking" and I really need to make sure that ok when I pass you this, I ned x back or I need y back.

So can you guys help me buy maybe giving me some examples, maybe some links to examples on how this type of code would be tested? Some real world stuff?

Aucun commentaire:

Enregistrer un commentaire