【发布时间】:2019-08-13 12:57:43
【问题描述】:
我正在尝试测试我的 Category 类。我正在使用 Mockery::mock() 方法,带有 'overload:' 前缀和 makePartial() 方法。
运行测试时出现此错误:
Mockery\Exception\BadMethodCallException : Method App\Models\Category::getDynamicFieldsForDocument() does not exist on this mock object
这是我的代码:
namespace App\Models;
class Category extends DictionaryBase{
//some methods
public function getDynamicFieldsForDocument()
{
$data = [];
$parents = [];
$allParents = $this->getParents($this->id, $parents);
foreach ($allParents as $parentId) {
$parent = Category::find($parentId);
$fields = $parent->dynamicFields();
foreach ($fields as $field) {
$data[$field['name']] = $field;
}
}
return $data;
}
}
测试用例:
namespace Tests\Unit;
use App\Models\Category;
use Tests\TestCase;
class CategoryModelTest extends TestCase{
//some methods
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testGetDynamicFieldsForDocument()
{
$mockCategory = \Mockery::mock('overload:'.Category::class)->makePartial();
$preparedDynamicFields = $this->prepareDynamicFields();
$preparedCategories = $this->prepareCategories();
$mockCategory->shouldReceive('find')->andReturn($preparedCategories[0], $preparedCategories[1], $preparedCategories[2]);
$mockCategory->shouldReceive('getParents')->andReturn(['1a2b', '3c4d', '5e6f']);
$mockCategory->shouldReceive('dynamicFields')->andReturn(null, $preparedDynamicFields[0], $preparedDynamicFields[1]);
$response = $mockCategory->getDynamicFieldsForDocument();
dd($response);
}
}
我不知道为什么我仍然有错误。我认为当调用 ->makePartial() 方法时,它应该只模拟由 ->shouldReceive() 调用的方法
编辑:
现在我正在制作没有 :overload 的模拟实例,并以这种方式模拟 'find' 方法:
`$mockCategory->shouldReceive('find')->andReturn($preparedCategories[0], $preparedCategories[1], $preparedCategories[2]);`
我的 find 方法如下所示:
public static function find($id) {
return $id ? self::list(config(static::IDENT.'.fields'), (new Filter('and'))->add('id', $id, '')->toArray(),[],1,1)[0] ?? null : null;
}
这是我的错误:
错误:App\Exceptions\ApiException([string $message [, long $code [, Throwable $previous = NULL]]])
这是因为 list 方法调用 API,所以看起来这个方法是在没有 mock 的情况下调用的。 我知道我不能模拟静态方法,但是在我之前使用 :overload 时它是可能的。现在做什么?
【问题讨论】:
-
你能发布你的 Category 模型和 CategoryModelTest 类的命名空间吗?还要检查测试文件中的
use声明。 -
我更新了我的帖子,你现在可以看到它了
标签: php laravel unit-testing phpunit mockery