使用mockery测试Laravel控制器时出错:在非对象上调用成员函数fetchMock()

时间:2014-06-11 19:43:37

标签: laravel mockery

在使用Laravel 4.2中的控制器的Mockery(dev-master)进行PHPUnit测试时,我收到以下错误:

致命错误:在第129行的\ laravel \ vendor \ mockery \ mockery \ library \ Mockery.php中的非对象上调用成员函数fetchMock()

控制器和测试如下:

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
}

此测试在没有Mockery的情况下正常工作(即不执行$this->app->instance('User', $this->mock);

执行时, fetchMock 函数内部会引发错误 return self::$_container->fetchMock($name);

以下是fetchMock失败时在调试器中可见的值:

enter image description here

导致此错误的原因是什么?

1 个答案:

答案 0 :(得分:3)

使用此方法替换__construct方法,然后重试:

public function setUp() {
    parent::setUp();
    $this->mock = Mockery::mock('Eloquent', 'User');
}