Mocking Laravel Eloquent models - how to set a public property with Mockery Mocking Laravel Eloquent models - how to set a public property with Mockery laravel laravel

Mocking Laravel Eloquent models - how to set a public property with Mockery


If you want getting this property with this value, just use it:

$mock->shouldReceive('getAttribute')    ->with('role')    ->andReturn(2);

If you call $user->role you will get - 2 ($user - its User mock class)


This answer is a bit late but hopefully it will help someone. You can currently set a static property on mocked Eloquent objects by using the 'alias' keyword:

$mocked_model = Mockery::mock('alias:Namespace\For\Model');$mocked_model->foo = 'bar';$this->assertEquals('bar', $mocked_model->foo);

This is also helpful for mocking external vendor classes like some of the Stripe objects.

Read about 'alias' and 'overload' keywords:http://docs.mockery.io/en/latest/reference/startup_methods.html


To answer your question, you could also try something like this:

$mock = Mockery::mock('User');$mock->shouldReceive('hasRole')->once()->andReturn(true); //works fine$mock->shouldReceive('setAttribute')->passthru();$mock->roles = 2; $mock->shouldReceive('getAttribute')->passthru();$this->assertEquals(2, $mock->roles);

Or, as suggested by seblaze, use a partial mock:

$mock = Mockery::mock('User[hasRole]');$mock->shouldReceive('hasRole')->once()->andReturn(true);$mock->roles = 2; $this->assertEquals(2, $mock->roles);

But, from your code snippet, if you're writing unit tests, you should really only make one assertion per each test:

function test_someFunctionWhichCallsHasRole_CallsHasRole() {    $mock = Mockery::mock('User');    $mock->shouldReceive('hasRole')->once();    $mock->someFunctionWhichCallsHasRole();}function test_someFunctionWhichCallsHasRole_hasRoleReturnsTrue_ReturnsTrue() {    $mock = Mockery::mock('User');    $mock->shouldReceive('hasRole')->once()->andReturn(true);    $result = $mock->someFunctionWhichCallsHasRole();    $this->assertTrue($result);}