gpt4 book ai didi

php - 使用 phpunit 和 Mockery 模拟 Laravel 5.2 本地范围

转载 作者:搜寻专家 更新时间:2023-10-31 21:25:50 26 4
gpt4 key购买 nike

我正在使用 Laravel 5.2、phpunit 5.0.0 和 PHP 7.0.3,并尝试编写一个涉及 Eloquent 模型范围方法的数据库交互测试。

我有一个类似的东西:

class Picture extends Illuminate\Database\Eloquent\Model {
...
public function scopeGetPictureNameById($oQuery, $pictureHId) {
return $oQuery->select('name')->where('h_id', '=', $pictureHId)->first()->name;
}
}

class someHelperClass {
public function someMethod($pictureId) {
$pictureName = Picture::getPictureNameById($pictureId);
return "name is " . $pictureName;
}
}


class SomeTest extends TestCase {

use DatabaseMigrations;

protected $someHelper;

public function setUp() {
parent::setUp();
$this->someHelper = new SomeHelper();
}

/**
* @test
*/
public function someMethodTest() {
$expectedName = "test";
$this->assertEquals("name is " . $expectedName, $this->someHelper->someMethod());
}
}

我用名称设置为“test”的图片记录为数据库播种。

我首先想到的是我不必模拟作用域调用,因为我需要的只是在数据库中。而且由于我的(非简化)代码在测试之外工作,我猜范围调用在 phpunit 中不起作用。(我收到“试图获取非对象的属性”异常)。

好的,所以我尝试用 Mockery 来模拟调用:

class SomeTest extends TestCase {

use DatabaseMigrations;

protected $someHelper;

public function setUp() {
parent::setUp();
$this->someHelper = new SomeHelper();
}

/**
* @test
*/
public function someMethodTest() {
$expectedName = "test";

$mockedPicture = Mockery::mock('overload:App\Models\Picture');
$mockedPicture->shouldReceive('getPictureNameById')->andReturn('test');

//also tried this: $mockedPicture->shouldReceive('scopeGetPictureNameById')->andReturn('test');


$this->assertEquals("name is " . $expectedName, $this->someHelper->someMethod());
}
}

我得到的只是“无法加载模拟 App\Models\Picture,类已经存在”。那么我怎样才能正确模拟查询范围调用,如 Picture::getPictureNameById($pictureId)?

最佳答案

我会使用依赖注入(inject)而不是静态调用 Picture 类的方法。所以像这样:

class someHelperClass {

protected $picture;

public function __construct(Picture $picture) {
$this->picture = $picture;
}

public function someMethod($pictureId) {
$pictureName = $this->picture->getPictureNameById($pictureId);
return "name is " . $pictureName;
}
}

然后在你的测试中:

public function someMethodTest() {
$expectedName = "test";

$mockedPicture = Mockery::mock('App\Models\Picture');
$mockedPicture->shouldReceive('getPictureNameById')->andReturn('test');
$someHelper = new SomeHelper($mockedPicture);

$this->assertEquals("name is " . $expectedName, $someHelper->someMethod(1));
}

关于php - 使用 phpunit 和 Mockery 模拟 Laravel 5.2 本地范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36375133/

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