How to mock static methods of a Laravel Eloquent model? How to mock static methods of a Laravel Eloquent model? laravel laravel

How to mock static methods of a Laravel Eloquent model?


You should do something like this:

$client_mock = \Mockery::mock('overload:App\Models\ModelName');$client_mock->shouldReceive('create')->with($data)->andReturn($returnValue);

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:

/** * @runTestsInSeparateProcesses * @preserveGlobalState disabled */

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 classes using this method. In those cases you can create a normal mock (without overload) and inject it to the service container like so:

App::instance('\App\Models\ModelName', $client_mock);