gpt4 book ai didi

php - 在 Mockery 中测试链式方法调用

转载 作者:可可西里 更新时间:2023-11-01 12:23:48 24 4
gpt4 key购买 nike

我正在尝试在 Controller 中正确模拟对 Eloquent 模型的链式调用。在我的 Controller 中,我使用依赖注入(inject)来访问模型,以便模拟它应该很容易,但是我不确定如何测试链接调用并使其正常工作。这一切都在 Laravel 4.1 中使用 PHPUnit 和 Mockery。

Controller :

<?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'));
}
}

Controller 测试:

<?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 测试这个链式方法调用的最佳方法是什么。

最佳答案

最初是一条评论,但后来为了让代码清晰可读而移动到回答!

我倾向于@alexrussell's answer同样,尽管中间立场是:

$this->mock->shouldReceive('remember->with->notSold->take->orderBy->get')
->andRe‌​turn($this->collection);

关于php - 在 Mockery 中测试链式方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21743467/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com