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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With