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

mtmacdonald picture mtmacdonald · Apr 7, 2014 · Viewed 18.3k times · Source

I want to use a mock object (Mockery) in my PHPUnit test. The mock object needs to have both some public methods and some public properties set. The class is a Laravel Eloquent model. I tried this:

$mock = Mockery::mock('User');
$mock->shouldReceive('hasRole')->once()->andReturn(true); //works fine
$mock->roles = 2; //how to do this? currently returns an error
$this->assertTrue(someTest($mock));

... but setting the public property returns this error:

BadMethodCallException: Method Mockery_0_User::setAttribute() does not exist on this mock object

This error is not returned when mocking a simple class, but is returned when I try to mock an Eloquent model. What am I doing wrong?

Answer

Joyful picture Joyful · Oct 24, 2014

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)