How to mock Laravel eloquent's accessor attribute

I'm doing unit tests in my Laravel 4 application, but I'm stuck in mocking access attributes.

I have a model Eloquentin which there is an attribute Accessor. I am trying to mock this model and return a value when this accessor attribute is called. But I cannot find a solution for this to work.

My super simple custom class.

class User extends Eloquent {
    public function getFullNameAttribute() {
        return $this->first_name . ' ' . $this->last_name;
    }
}

I tried the following:

$user_mock = m::mock('MyApp\Models\User');

$user_mock->shouldReceive('__get')->with('full_name')->andReturn('John Snow'); // doesn't work
$user_mock->shouldReceive('getAttribute')->with('full_name')->andReturn('John Snow'); // doesn't work
$user_mock->shouldReceive('getFullNameAttribute')->andReturn('John Snow'); // doesn't work

echo $user_mock->full_name; // --> " "

I just get the empty space back, indicating that the function is still being called.

+4
source share
2 answers

. " , ". Laravel , , .

, , . , , - ( ).

, , :

public function getFirstNameAttribute()
{
     return app(UserRepository::class)->getFirstName($this);
}

, . , , , .

+1

Mockery, , . , :

$user_mock = m::mock('MyApp\Models\User');
$user_mock->first_name = 'John Snow';

mockery

-2

All Articles