Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when testing Laravel controller with mockery: Call to a member function fetchMock() on a non-object

I receive the following error when making a PHPUnit test with Mockery (dev-master) of the controller in Laravel 4.2 :

Fatal error: Call to a member function fetchMock() on a non-object in \laravel\vendor\mockery\mockery\library\Mockery.php on line 129

The controller and test are as follows:

class UserControllerTest extends TestCase {
  public function __construct() {
    $this->mock = Mockery::mock('Eloquent', 'User');
  }
  function tearDown() {
    Mockery::close();
  }
  public function testIndex() {
    $this->mock
      ->shouldReceive('all')
      ->once()
      ->andReturn('foo');
    $this->app->instance('User', $this->mock);
    $response = $this->action('GET', 'UserController@index');
    //other stuff
  }
}

class UserController extends \BaseController {
  protected $user;
  public function __construct(User $user) {
    $this->user = $user;
  }
  public function index() {
    $users = $this->user->all();
    return View::make('users.index', ['users' => $users]);
  }
  //other stuff
}

This test works ok without Mockery (i.e. without executing $this->app->instance('User', $this->mock); )

The error is raised inside fetchMock function, when executing return self::$_container->fetchMock($name);

Here are the values visible in debugger inside fetchMock when it fails:

enter image description here

What is causing this error?

like image 696
camcam Avatar asked Aug 31 '25 01:08

camcam


1 Answers

Replace __construct method using this and try again:

public function setUp() {
    parent::setUp();
    $this->mock = Mockery::mock('Eloquent', 'User');
}
like image 95
The Alpha Avatar answered Sep 03 '25 15:09

The Alpha