Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phpunit testing Laravel controller

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?

like image 684
TJ is too short Avatar asked Oct 29 '22 22:10

TJ is too short


1 Answers

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.

like image 102
Bostjan Avatar answered Nov 12 '22 18:11

Bostjan