Laravel mockery Laravel mockery laravel laravel

Laravel mockery


You can't directly mock an Eloquent class. Eloquent is not a Facade and your User model neither. There is a bit of magic in Laravel but you can't do things like that.

If you want to mock your User class, you have to inject it in the controller constructor. The repository pattern is a good approach if you want to do that. There is a lot of articles about this pattern and Laravel on Google.

Here some pieces of code to show you how it could look like :

class UserController extends BaseController {    public function __construct(UserRepositoryInterface $users)    {        $this->users = $users;    }    public function index()    {        $users = $this->users->all();        return View::make('user.index', compact('users'));    }}class UserControllerTest extends TestCase{    public function testIndex()    {        $repository = m::mock('UserRepositoryInterface');        $repository->shouldReceive('all')->andReturn(new Collection(array(new User, new User)));        App::instance('UserRepositoryInterface', $repository);        $this->call('GET', 'users');    }}

If it seems to be too much structuration for your project you can just call a real database in your tests and don't mock your model classes... In a classic project, it just works fine.


This function is part of a project called apiato.io you can use it to mock any class in Laravel, even facade, basically anything that can be resolved with the IoC, which is almost all classes if you are using proper dependency injection:

/** * Mocking helper * * @param $class * * @return  \Mockery\MockInterface */public function mock($class){    $mock = Mockery::mock($class);    App::instance($class, $mock);    return $mock;}