gpt4 book ai didi

phpunit - 用 find() 模拟 Eloquent 模型

转载 作者:行者123 更新时间:2023-12-04 03:58:36 25 4
gpt4 key购买 nike

我试图用 mock 来模拟 Eloquent 模型。模型通过注入(inject) Controller

__construct(Post $model){$this->model=$model}

现在我调用 find() Controller 中的功能
$post = $this->model->find($id);

这是 PostsController 的测试
class PostsTest extends TestCase{

protected $mock;

public function setUp() {
parent::setUp();
$this->mock = Mockery::mock('Eloquent', 'Posts'); /*According to Jeffrey Way you have to add Eloquent in this function call to be able to use certain methods from model*/
$this->app->instance('Posts', $this->mock);
}

public function tearDown() {

Mockery::close();
}

public function testGetEdit()
{
$this->mock->shouldReceive('find')->with(1)->once()->andReturn(array('id'=>1));

$this->call('GET', 'admin/posts/edit/1');

$this->assertViewHas('post', array('id'=>1));
}
}

运行 PhpUnit 给我错误:
Fatal error: Using $this when not in object context in ...\www\l4\vendor\mockery\mockery\library\Mockery\Generator.php(130) : eval()'d code on line 73

这显然是因为 find()被声明为静态函数。现在,代码可以正常工作,所以我怎样才能成功地模拟 Eloquent 模型而不会失败。由于我们依赖于依赖注入(inject),我必须调用 find()非静态的,否则我只能做 Post::find() .

我想出的一种解决方案是创建一个非静态 find() BaseModel 中的替换
public function nsFind($id, $columns = array('*'))
{
return self::find($id, $columns);
}

但这是一个很大的痛苦,因为函数必须有不同的名称!

我做错了什么还是你有更好的想法?

最佳答案

模拟 Eloquent 模型是一件非常棘手的事情。它在书中有所介绍,但我特别指出这是一个权宜之计。最好使用存储库。

但是,要回答您的问题,问题是您没有在构造函数中执行模拟。这是让它工作的唯一方法。这并不理想,我不会推荐它。

关于phpunit - 用 find() 模拟 Eloquent 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17008637/

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