我試圖在控制器中正確地模擬對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