Support the ongoing development of Laravel.io →
IOC Testing

I have a controller end point 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 = \GuzzleHttp\Psr7\stream_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(
            $rovi->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 = \GuzzleHttp\Psr7\stream_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.

Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

beerbuddha beerbuddha Joined 24 May 2016

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.