mercredi 22 juin 2016

Using Mock objects in Integrated Tests inside Laravel

I have a controller end point in Laravel that utilizes Guzzle

I have written a wrapper around the Guzzle Client and then created a ServiceProvider.

$this->app->singleton('guzzleclient', function ($app) {
    return  new Client([
        // Base URI is used with relative requests
        'base_uri' => $app['config']['api']['url'],
        // You can set any number of default request options.
        'timeout'  => 3.0,
    ]);
});
$this->app->singleton('client', function ($app) {
    return new ClientAdapter($app['guzzleclient']);
});

This approach of DI enables me to UnitTest my Adapter class with Guzzle being mock like the following from the Guzzle dock: http://docs.guzzlephp.org/en/latest/testing.html

 $stream = GuzzleHttpPsr7stream_for('string data');

        // Create a mock and queue two responses.
        $mock = new MockHandler([
            new Response(200, [], $stream),
            new Response(200, ['Content-Length' => 0]),
            new RequestException("Error Communicating with Server", new Request('GET', '/'))
        ]);

        $handler = HandlerStack::create($mock);
        $client = new Client(['handler' => $handler]);

        $adapter = new ClientAdapter('','',$client);

        // The first request is intercepted with the first response.
        $this->assertEquals(
            $adapter->getInfo([])->getStatusCode(),
            200
        );

this works, now my problem - (and its problaby from concept on how to utlize IoC and DI)

I want to start doing integrated test, where I would call my controller and swap out the Guzzle call with my MockData and test the controller component.

 $stream = GuzzleHttpPsr7stream_for('string data');
// ... init MockHandler...
// ....
    public function testExample()
    {
        $this->get('/');

        $this->assertEquals(
            $this->response->getContent(), 'string data'
        );
    }

However since the controller utilizes app('client'); the IoC initilizes the $client from the IoC (which in product it is what i want) but in testing, how do I ensure that the one that i want to Mock up as seen above is that one that gets invoked and not the one from the IoC? That is where I am stumped.

Aucun commentaire:

Enregistrer un commentaire