Havocbringer

Experience

170

0 Best Reply Awards

  • Member Since 1 Month Ago
  • 1 Lesson Completed
  • 0 Favorites

14th June, 2018

Havocbringer left a reply on Mocking Eloquent Queries • 1 month ago

That's what I was afraid of ... So the best option remains to separate the DB extraction and just test the methods independently?

Havocbringer left a reply on Mocking Eloquent Queries • 1 month ago

No, this is a simplified example, I am just trying to get it to work.

I want to be able to test methods that call the database internally. In order to be able to do so, I want to intercept the DB calls by using Mockery.

I have no problems in calling the actual test database but that would not be "unit testing".

Havocbringer started a new conversation Mocking Eloquent Queries • 1 month ago

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);
    $mockedUser->shouldReceive('where')->with('id',5)->andReturn($mockedBuilder);

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

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

What am I doing wrong?

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.