我正在尝试在控制器中正确模拟对 Eloquent 模型的链式调用。在我的控制器中,我使用依赖注入来访问模型,以便它应该易于模拟,但是我不确定如何测试链接调用并使其正常工作。这一切都在使用 PHPUnit 和 Mockery 的 Laravel 4.1 中。
控制器:
<?php
class TextbooksController extends BaseController
{
protected $textbook;
public function __construct(Textbook $textbook)
{
$this->textbook = $textbook;
}
public function index()
{
$textbooks = $this->textbook->remember(5)
->with('user')
->notSold()
->take(25)
->orderBy('created_at', 'desc')
->get();
return View::make('textbooks.index', compact('textbooks'));
}
}
控制器测试:
<?php
class TextbooksControllerText extends TestCase
{
public function __construct()
{
$this->mock = Mockery::mock('Eloquent', 'Textbook');
}
public function tearDown()
{
Mockery::close();
}
public function testIndex()
{
// Here I want properly mock my chained call to the Textbook
// model.
$this->action('GET', 'TextbooksController@index');
$this->assertResponseOk();
$this->assertViewHas('textbooks');
}
}
我一直试图通过将此代码放在$this->action()
测试中的调用之前来实现这一点。
$this->mock->shouldReceive('remember')->with(5)->once();
$this->mock->shouldReceive('with')->with('user')->once();
$this->mock->shouldReceive('notSold')->once();
$this->app->instance('Textbook', $this->mock);
但是,这会导致错误Fatal error: Call to a member function with() on a non-object in /app/controllers/TextbooksController.php on line 28
。
我还尝试了一种链式替代方案,希望它能起到作用。
$this->mock->shouldReceive('remember')->with(5)->once()
->shouldReceive('with')->with('user')->once()
->shouldReceive('notSold')->once();
$this->app->instance('Textbook', $this->mock);
用 Mockery 测试这个链式方法调用的最佳方法是什么。