Mocking Eloquent Queries

Posted 8 months ago by Havocbringer

Hello guys,

I am trying to catch up with Unit Tests. The problem is, 99% of our DB queries are using static methods of the Eloquent models, e.g.: User::join(...)->where(...)->get()

Is there any way to mock these DB calls? I seem to be hitting a rock with PHPUnit and Mockery.

Here's an example (everything is deliberately crammed inside a single method):

/** @test */
public function example()
    $mockedUser = \Mockery::mock(\App\Models\Admin\User::class);
    $this->app->instance(\App\Models\Admin\User::class, $mockedUser);
    $mockedBuilder = \Mockery::mock(\Illuminate\Database\Eloquent\Builder::class);
    $this->app->instance(\Illuminate\Database\Eloquent\Builder::class, $mockedUser);

    $emptyUser = new \App\Models\Admin\User();
    $emptyUser->id = 2;

    $newUser = \App\Models\Admin\User::where('id',5)->first();
    $this->assertEquals($emptyUser->id, $newUser->id);

What am I doing wrong? Is it possible to mock such queries without dependency injection or separating the DB extraction layer?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.