I have in my code a line like this:
ModelName::create($data);
where ModelName is just an Eloquent
model. Is there a way to mock this call inside a unit test? I tried with:
$client_mock = \Mockery::mock('Eloquent','App\Models\ModelName');
$client_mock->shouldReceive('create')
->with($data)->andReturns($returnValue);
but it doesn't work.
You should do something like this:
We are using
overload:
because you don't want to pass mock to some class, but you want to use it also in case it's hard-coded into some classes.In addition to your test class (just before
class
) you should add:to avoid errors that this class was already loaded (it might work without it in single test but when you are running multiple tests probably it won't).
You might read Mocking hard dependencies for details about it.
UPDATE
In some cases it might be not possible to mock class using this method. In those cases you can create normal mock (without
orverload
) and inject it to service container like so: