我正在测试我的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;
}
}
TestCase:
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]);`
我的查找方法如下:
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]]])
这是因为列表方法调用API,所以看起来该方法是在没有模拟的情况下调用的。 我知道我不能模拟静态方法,但是在我使用:overload时,这是可能的。现在做什么?
答案 0 :(得分:0)
删除:overload
,然后将模拟定义为:
$mockCategory = \Mockery::mock(Category::class)->makePartial()
示例
型号:
namespace App\Models;
class Foobar extends BaseModel
{
public function foonction()
{
Foobar::find();
return '1';
}
}
测试:
命名空间测试;
use Evalua\Heva\Models\Foobar;
class FoobarTest extends TestCase
{
public function testFoobar()
{
$fooMock = \Mockery::mock('overload:'.Foobar::class)->makePartial();
$fooMock->shouldReceive('find')->once();
$fooMock->foonction();
}
}
失败:
Mockery\Exception\BadMethodCallException: Method Evalua\Heva\Models\Foobar::foonction() does not exist on this mock object
没有:overload
测试通过。
说明应为based on what's written in the documentation about overload:
使用“ overload:”前缀一个类的有效名称(当前未加载)会生成一个别名模拟(与“ alias:”一样),只是创建该类的新实例将导入该类的所有期望值。原始模拟($ mock)。原始模拟未经验证,因为它为新实例使用了期望存储。为此,我们使用术语“实例模拟”