我试图在控制器中正确地模拟对Eloquent模型的链接调用。在我的控制器中,我使用依赖注入来访问模型,所以它应该很容易模拟,但是我不确定如何测试链式调用并使其正确工作。这一切都在Laravel 4.1中使用PHPUnit和Mockery。在Mockery中测试链式方法调用
控制器:
<?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', '[email protected]');
$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这种链式方法调用。
请阅读文档 https://github.com/padraic/mockery#mocking-demeter-chains-and-fluent - 接口 – Shakil