コントローラー内の 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 でテストするために取るべき最善のアプローチは何ですか。