5

I'm building a small Laravel application and I would like test it using phpunit. Is a very simple application with one controller:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use GuzzleHttp\Client;

class MyController extends Controller
{
    protected $client;

    public function __construct(Client $client)
    {
        $this->client = $client;
    }

    public function doSomething(Request $request)
    {
        ...

        $this->client->post(...);

        ...
    }
}

So, as you can see I'm passing the Guzzle object in the controller (my idea is to replace that client with a mock handler. I want to test if the function doSomething is doing what I'm expecting but I don't know how to call it.

I can easily (in my MyControllerTest) do something like:

$controller = new MyController($fakeGuzzleObject);

but then, how can I call doSomething and pass a Request instance?

Alternatively I can do something like:

$this->get(route/to/access/doSomething)

And let Laravel inject the Request, but how can I tell it to use a mocked Guzzle instance?

1
  • I think you can $this->app->instance(Client::class, new FakeClient) inside your test. Commented Dec 2, 2017 at 20:45

1 Answer 1

2

Both options are quite simple.

First options:

You can call controller action like $controller->doSomething(new Request(['data' => 'data']))

Second option:

If you do $this->get(...) and want custom class to be injected in constructor just bind it:

$this->app->bind(\GuzzleHttp\Client::class, function () { $client = new GuzzleHttp\Client(); });

I suggest using second option.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks very much for your answer. The second option can be done inside MyControllerTest class? I mean, can I do it anywhere on that class or only in the setUp method?
you can do it anywhere in the class, but before you make get request

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.