在使用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失败时在调试器中可见的值:
导致此错误的原因是什么?
答案 0 :(得分:3)
使用此方法替换__construct
方法,然后重试:
public function setUp() {
parent::setUp();
$this->mock = Mockery::mock('Eloquent', 'User');
}